Commit 5465bd4a authored by qiwanqing's avatar qiwanqing Committed by qiwanqing

自定义登录、授权页面

parent b4c0d038
...@@ -30,22 +30,11 @@ ...@@ -30,22 +30,11 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <!-- oauth -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--&lt;!&ndash; oauth &ndash;&gt;
<dependency> <dependency>
<groupId>org.springframework.security.oauth</groupId> <groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId> <artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version> <version>2.3.3.RELEASE</version>
</dependency>-->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.3.RELEASE</version>
</dependency> </dependency>
<!-- security --> <!-- security -->
...@@ -77,24 +66,6 @@ ...@@ -77,24 +66,6 @@
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<!--swagger start-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger end-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.yingxin.server.client.config; package com.yingxin.server.client.config;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -7,17 +8,14 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; ...@@ -7,17 +8,14 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.annotation.Resource;
import javax.sql.DataSource;
/** /**
* description//TODO * description//TODO
...@@ -38,11 +36,15 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfig ...@@ -38,11 +36,15 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfig
@Autowired @Autowired
UserDetailsService myUserDetailsService; UserDetailsService myUserDetailsService;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired @Autowired
ClientDetailsService myClientDetailsService; ClientDetailsService myClientDetailsService;
@Bean @Bean
public RedisTokenStore redisTokenStore(){ public RedisTokenStore tokenStore(){
return new RedisTokenStore(connectionFactory); return new RedisTokenStore(connectionFactory);
} }
...@@ -77,7 +79,7 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfig ...@@ -77,7 +79,7 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfig
@Override @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager) endpoints.authenticationManager(authenticationManager)
.tokenStore(new RedisTokenStore(connectionFactory)) .tokenStore(tokenStore())
.userDetailsService(myUserDetailsService) .userDetailsService(myUserDetailsService)
.allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST); .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
} }
......
...@@ -3,18 +3,15 @@ package com.yingxin.server.client.config; ...@@ -3,18 +3,15 @@ package com.yingxin.server.client.config;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/** /**
* description//TODO * description//TODO
* *
...@@ -23,14 +20,12 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; ...@@ -23,14 +20,12 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
* @date 2019/8/20 * @date 2019/8/20
*/ */
@EnableWebSecurity //开启权限验证 @EnableWebSecurity //开启权限验证
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
private UserDetailsService myUserDetailsService; private UserDetailsService myUserDetailsService;
@Autowired
private MySecurityProperties properties;
/** /**
* 配置这个bean会在做AuthorizationServerConfigurer配置的时候使用 * 配置这个bean会在做AuthorizationServerConfigurer配置的时候使用
* @return * @return
...@@ -47,39 +42,28 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -47,39 +42,28 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder()); auth.userDetailsService(myUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
} }
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers
("/swagger-ui.html/**", "/webjars/**",
"/swagger-resources/**", "/v2/api-docs/**",
"/swagger-resources/configuration/ui/**", "/swagger-resources/configuration/security/**",
"/images/**");
}
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http
// 必须配置,不然OAuth2的http配置不生效 // 必须配置,不然OAuth2的http配置不生效
.requestMatchers() .requestMatchers()
.antMatchers( "/oauth/**",properties.getLoginProcessUrl(),properties.getLoginPage()) .antMatchers( "/oauth/**","/auth/authorize","/auth/login")
.and() .and()
.authorizeRequests() .authorizeRequests()
// 自定义页面或处理url时,如果不配置全局允许,浏览器会提示服务器将页面转发多次 // 自定义页面或处理url时,如果不配置全局允许,浏览器会提示服务器将页面转发多次
.antMatchers("/auth/login",properties.getLoginProcessUrl()) .antMatchers("/auth/login","/auth/authorize","/oauth/**")
.permitAll() .permitAll()
.anyRequest() .anyRequest()
.authenticated(); .authenticated();;
// 表单登录 // 表单登录
http.formLogin() http.formLogin()
// 登录页面 // 登录页面
.loginPage(properties.getLoginPage()) .loginPage("/auth/login")
.loginProcessingUrl(properties.getLoginProcessUrl()); .loginProcessingUrl("/auth/authorize");
http.httpBasic().disable(); http.httpBasic().disable();
} }
} }
...@@ -43,10 +43,13 @@ public class CallbackController { ...@@ -43,10 +43,13 @@ public class CallbackController {
private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass()); private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
//获取code后,自动提交post请求获取token,取出token,直接获取资源
@RequestMapping("/oauth/callback") @RequestMapping("/oauth/callback")
public Map getToken(@RequestParam(value = "code") String code, Principal principal){ public Map getToken(@RequestParam(value = "code") String code, Principal principal){
//放开后,可获取角色
//String role=userService.findRoleByUsername(principal.getName()).iterator().next().getRole_name(); //String role=userService.findRoleByUsername(principal.getName()).iterator().next().getRole_name();
//System.out.println(role); //System.out.println(role);
String clientId="client1"; String clientId="client1";
logger.info("receive code {}",code); logger.info("receive code {}",code);
...@@ -54,6 +57,7 @@ public class CallbackController { ...@@ -54,6 +57,7 @@ public class CallbackController {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String,String> params= new LinkedMultiValueMap<>(); MultiValueMap<String,String> params= new LinkedMultiValueMap<>();
//获取token
List<Client> clients=clientService.findClientByCLientId(clientId); List<Client> clients=clientService.findClientByCLientId(clientId);
params.add("grant_type","authorization_code"); params.add("grant_type","authorization_code");
params.add("code",code); params.add("code",code);
...@@ -61,16 +65,16 @@ public class CallbackController { ...@@ -61,16 +65,16 @@ public class CallbackController {
params.add("client_secret",clients.get(0).getClientSecret()); params.add("client_secret",clients.get(0).getClientSecret());
params.add("redirect_uri",clients.get(0).getWebServerRedirectUri()); params.add("redirect_uri",clients.get(0).getWebServerRedirectUri());
HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<>(params, headers); HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<>(params, headers);
//System.out.println(requestEntity.toString());
ResponseEntity<Map> response = restTemplate.postForEntity("http://localhost:8080/oauth/token",requestEntity,Map.class); ResponseEntity<Map> response = restTemplate.postForEntity("http://localhost:8080/oauth/token",requestEntity,Map.class);
Map token = response.getBody(); Map token = response.getBody();
logger.info("token => {}",token); logger.info("token => {}",token);
//从token中获取access_token
Map map=new HashMap(); Map map=new HashMap();
map.put("access_token",token.get("access_token").toString()); map.put("access_token",token.get("access_token").toString());
logger.info("access_token => {}",token.get("access_token").toString()); logger.info("access_token => {}",token.get("access_token").toString());
//处理401错误
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override @Override
public void handleError(ClientHttpResponse response) throws IOException { public void handleError(ClientHttpResponse response) throws IOException {
...@@ -80,6 +84,7 @@ public class CallbackController { ...@@ -80,6 +84,7 @@ public class CallbackController {
} }
}); });
//提交get请求,获取资源
ResponseEntity<Map> responseEntity=restTemplate.getForEntity("http://localhost:8088/user?access_token={access_token}",Map.class,map); ResponseEntity<Map> responseEntity=restTemplate.getForEntity("http://localhost:8088/user?access_token={access_token}",Map.class,map);
return responseEntity.getBody(); return responseEntity.getBody();
......
...@@ -11,9 +11,9 @@ import java.util.Map; ...@@ -11,9 +11,9 @@ import java.util.Map;
@Controller @Controller
@SessionAttributes("authorizationRequest") @SessionAttributes("authorizationRequest")
public class GrantController { public class GrantController {
//自定义授权页面
@RequestMapping(value = "/oauth/confirm_access") @RequestMapping(value = "/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model,HttpServletRequest request) throws Exception { public ModelAndView getAccessConfirmation(Map<String, Object> model,HttpServletRequest request) throws Exception {
AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest"); AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
...@@ -22,7 +22,6 @@ public class GrantController { ...@@ -22,7 +22,6 @@ public class GrantController {
view.setViewName("grant"); view.setViewName("grant");
view.addObject("clientId",clientId ); view.addObject("clientId",clientId );
view.addObject("scopes",authorizationRequest.getScope()); view.addObject("scopes",authorizationRequest.getScope());
System.out.println(authorizationRequest.toString());
return view; return view;
} }
} }
package com.yingxin.server.client.controller; package com.yingxin.server.client.controller;
import com.yingxin.server.client.config.MySecurityProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
...@@ -9,13 +9,10 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -9,13 +9,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller @Controller
public class LoginController { public class LoginController {
@Autowired //自定义登录页面
private MySecurityProperties properties;
@RequestMapping("/auth/login") @RequestMapping("/auth/login")
public String login(Model model) { public String login(Model model) {
//System.out.println(properties.getLoginProcessUrl()); model.addAttribute("loginProcessUrl","/auth/authorize");
model.addAttribute("loginProcessUrl",properties.getLoginProcessUrl());
return "login"; return "login";
} }
......
...@@ -74,9 +74,11 @@ ...@@ -74,9 +74,11 @@
</div> </div>
<script th:inline="javascript"> <script th:inline="javascript">
window.onload=function(){ window.onload=function(){
document.getElementsByName("span")[0].innerText=document.getElementsByName("span")[0].id; for(var i = 0;i<3;i++){
document.getElementsByName("span")[i].innerText=document.getElementsByName("span")[i].id;
}
} }
</script> </script>
</body> </body>
</html> </html>
\ No newline at end of file
...@@ -6,11 +6,10 @@ server: ...@@ -6,11 +6,10 @@ server:
security: security:
oauth2: oauth2:
client: client:
access-token-uri: ${auth-server-url}/oauth/token
user-authorization-uri: ${auth-server-url}/oauth/authorize
client-id: client1 client-id: client1
client-secret: 123456 client-secret: 123456
scope: test scope: test
access-token-uri: ${auth-server-url}/oauth/token
user-authorization-uri: ${auth-server-url}/oauth/authorize
resource: resource:
token-info-uri: ${auth-server-url}/oauth/check_token #检查令牌 token-info-uri: ${auth-server-url}/oauth/check_token #检查令牌
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment