OAuth2整合Spring Security 什么是OAuth2+代码+测试
什么是OAuth2 什么是OAuth2,整合redis,见Spring Security学习笔记 流程:
用户访问,此时没有Token。Oauth2RestTemplate会报错,这个报错信息会被Oauth2ClientContextFilter捕获并重定向到认证服务器认证服务器通过Authorization Endpoint进行授权,并通过AuthorizationServerTokenServices生成授权码并返回给客户端客户端拿到授权码去认证服务器通过Token Endpoint调用AuthorizationServerTokenServices生成Token并返回给客户端客户端拿到Token去资源服务器访问资源,一般会通过Oauth2AuthenticationManager调用ResourceServerTokenServices进行校验。校验通过可以获取资源。代码 引pom
<properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR2</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>创建自定义登录
@Service public class UserService implements UserDetailsService { @Autowired private PasswordEncoder encoder; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { String encode = encoder.encode("123"); return new User("qgb",encode, AuthorityUtils .commaSeparatedStringToAuthorityList("admin")); } }配置SecurityConfig 配置类
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder getpw(){ return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/oauth/**","/login/**","/logout/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .permitAll(); } }配置授权服务器
//授权服务器配置 @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder encoder; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("admin") .secret(encoder.encode("123123")) //配置token有效日期 秒 .accessTokenValiditySeconds(3600) //配置授权成功跳转重定向uri .redirectUris("http://www.baidu.com") //配置申请的权限范围 .scopes("all") //配置GrantTypes表示授权类型 authorization-code授权码模式 .authorizedGrantTypes("authorization_code"); }}配置资源服务器
//资源服务器配置 @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest() .authenticated() .and() .requestMatchers() .antMatchers("/user/**"); } }写控制类获得当前用户主体
@RestController @RequestMapping("/user") public class UserController { @RequestMapping("/getCurrentUser") public Object getCurrentUser(Authentication authentication){ return authentication.getPrincipal(); } }测试 访问地址获取授权码http://localhost:8080/oauth/authorizeresponse_type=code&client_id=admin&redirect_uri=http://www.baidu.com&scope=all 用postman测试 就拿到了access_token,token字符串 访问资源服务器,用授权服务器给的access_token 获得当前用户主体 密码模式 修改AuthorizationServerConfig类
//授权模式改为密码模式 .authorizedGrantTypes("password");重写configure(AuthorizationServerEndpointsConfigurer endpoints)
//使用密码模式所需配置 @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .userDetailsService(userService); }修改参数 获取token访问资源,完成。