关于Ouath2

概述oauth

OAUTH,Open Authorization,开放授权协议,为用户资源的授权提供了一个安全的、开放而又简易的标准。目的是让第三方对用户的数据只有有限访问权,而无法触及到用户的核心信息。

例如,在第三方网站上使用微信或者QQ作为账号进行登录,就是使用的oauth协议,只返回给第三方诸如用户名、头像等信息,而不会返回给第三方秘密等核心数据。

OAuth最初由Twitter的开发人员提出,后来成为了一个互联网标准,并得到了广泛应用。OAuth2.0是OAuth协议的第二个版本,是一种更加安全、可扩展、功能更加完备的授权协议。目前我们说OAuth一般指的就是OAuth 2.0。

需要的maven依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.6.0</version>
        </dependency>
    </dependencies>

1、添加注解@EnableAuthorizationServer

2、继承AuthorizationServerConfigurerAdapter

3、EnableAuthorizationServer注解需要配置

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter{
 
}

@Configuration
@Import(TokenKeyEndpointRegistrar.class)
public class AuthorizationServerEndpointsConfiguration {
 
   private AuthorizationServerEndpointsConfigurer endpoints = new AuthorizationServerEndpointsConfigurer();
 
   @Autowired
   private ClientDetailsService clientDetailsService;
 
   @Autowired
   private List<AuthorizationServerConfigurer> configurers = Collections.emptyList();
 
   @PostConstruct
   public void init() {
      for (AuthorizationServerConfigurer configurer : configurers) {
         try {
            configurer.configure(endpoints);
         } catch (Exception e) {
            throw new IllegalStateException("Cannot configure enpdoints", e);
         }
      }
      endpoints.setClientDetailsService(clientDetailsService);
   }
 
//oauth/authorize
   @Bean
   public AuthorizationEndpoint authorizationEndpoint() throws Exception {
      AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
      FrameworkEndpointHandlerMapping mapping = getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
      authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
      authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
      authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
      authorizationEndpoint.setTokenGranter(tokenGranter());
      authorizationEndpoint.setClientDetailsService(clientDetailsService);
      authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
      authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
      authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
      authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
      authorizationEndpoint.setRedirectResolver(redirectResolver());
      return authorizationEndpoint;
   }
 
//oauth/token
   @Bean
   public TokenEndpoint tokenEndpoint() throws Exception {
      TokenEndpoint tokenEndpoint = new TokenEndpoint();
      tokenEndpoint.setClientDetailsService(clientDetailsService);
      tokenEndpoint.setProviderExceptionHandler(exceptionTranslator());
      tokenEndpoint.setTokenGranter(tokenGranter());
      tokenEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
      tokenEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
      tokenEndpoint.setAllowedRequestMethods(allowedTokenEndpointRequestMethods());
      return tokenEndpoint;
   }
 
//oauth/check_token
   @Bean
   public CheckTokenEndpoint checkTokenEndpoint() {
      CheckTokenEndpoint endpoint = new CheckTokenEndpoint(getEndpointsConfigurer().getResourceServerTokenServices());
      endpoint.setAccessTokenConverter(getEndpointsConfigurer().getAccessTokenConverter());
      endpoint.setExceptionTranslator(exceptionTranslator());
      return endpoint;
   }
 
//oauth/confirm_access
   @Bean
   public WhitelabelApprovalEndpoint whitelabelApprovalEndpoint() {
      return new WhitelabelApprovalEndpoint();
   }
 
//oauth/error
   @Bean
   public WhitelabelErrorEndpoint whitelabelErrorEndpoint() {
      return new WhitelabelErrorEndpoint();
   }
   ......
}

AuthorizationServerSecurityConfiguration:该类继承了WebSecurityConfigurerAdapter,提供了认证服务的一些相关配置,比如对访问/oauth/token、/oauth/token_key、/oauth/check_token请求要有相对应的访问权限,新增了AuthorizationServerSecurityConfigurer的可配置类,用来配置对token的认证请求过滤器,比如ClientCredentialsTokenEndpointFilter,该过滤器会拦截oauth/token请求,并且对client_id和client_secret进行认证。除此之外,还配置了对实现了AuthorizationServerConfigurer的类进行回调,这样的话,只要实现AuthorizationServerConfigurer接口就可以自由的对认证服务进行相关的业务配置。

@Configuration
@Order(0)
@Import({ ClientDetailsServiceConfiguration.class, AuthorizationServerEndpointsConfiguration.class })
public class AuthorizationServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
 
   @Autowired
   private List<AuthorizationServerConfigurer> configurers = Collections.emptyList();
 
   @Autowired
   private ClientDetailsService clientDetailsService;
 
   @Autowired
   private AuthorizationServerEndpointsConfiguration endpoints;
 
   @Autowired
   public void configure(ClientDetailsServiceConfigurer clientDetails) throws Exception {
      //回调AuthorizationServerConfigurer
      for (AuthorizationServerConfigurer configurer : configurers) {
         configurer.configure(clientDetails);
      }
   }
 
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     ...
   }
 
 //设置/oauth/token、/oauth/token_key、/oauth/check_token的认证规则
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      AuthorizationServerSecurityConfigurer configurer = new AuthorizationServerSecurityConfigurer();
      FrameworkEndpointHandlerMapping handlerMapping = endpoints.oauth2EndpointHandlerMapping();
      http.setSharedObject(FrameworkEndpointHandlerMapping.class, handlerMapping);
      configure(configurer);
      http.apply(configurer);
      String tokenEndpointPath = handlerMapping.getServletPath("/oauth/token");
      String tokenKeyPath = handlerMapping.getServletPath("/oauth/token_key");
      String checkTokenPath = handlerMapping.getServletPath("/oauth/check_token");
      if (!endpoints.getEndpointsConfigurer().isUserDetailsServiceOverride()) {
         UserDetailsService userDetailsService = http.getSharedObject(UserDetailsService.class);
         endpoints.getEndpointsConfigurer().userDetailsService(userDetailsService);
      }
      // @formatter:off
      http
           .authorizeRequests()
               .antMatchers(tokenEndpointPath).fullyAuthenticated()
               .antMatchers(tokenKeyPath).access(configurer.getTokenKeyAccess())
               .antMatchers(checkTokenPath).access(configurer.getCheckTokenAccess())
        .and()
           .requestMatchers()
               .antMatchers(tokenEndpointPath, tokenKeyPath, checkTokenPath)
        .and()
           .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
      // @formatter:on
      http.setSharedObject(ClientDetailsService.class, clientDetailsService);
   }
 
   protected void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
      //回调AuthorizationServerConfigurer
      for (AuthorizationServerConfigurer configurer : configurers) {
         configurer.configure(oauthServer);
      }
   }
 
}

  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值