AuthorizationServer:授权服务配置

AuthorizationServer:授权服务配置

一、授权服务配置类:AuthorizationServerConfigurerAdapter

– SpringSecurityOauth2提供了AuthorizationServerConfigurerAdapter适配器类来作为认证授权服务的配置,其中有三个方法,

– 客户端详情:配置客户端请求的参数;

– 授权服务断点:配置授权码和令牌的管理/存储方式;

– 授权服务安全配置:配置哪些路径放行(检查token的路径要放行);

二、搭建auth2授权服务配置

1.编写一个配置类: 继承AuthorizationServerConfigurerAdapter,

​ 开启认证配置服务标签:@EnableAuthorizationServer;

2.复写三个配置

​ 2.1 客户端详情配置:数据库创建一张表:auth_client_details 插入两条数据;

​ 定义一个JdbcClientDetailsService方法,需要两个参数:datasource,passwordEncoder;

​ 2.2 服务端点配置:

​ ①:配置认证管理器:在Security配置类中配置authenticationManager

​ ②:授权服务配置器:a:数据库创建一张表 auth_code

​ b:定义方法 JdbcAuthorizationCodeServices 需要一个参数datasource;

​ ③:令牌服务配置:new DefaultTokenService()

​ a: 设置客户端详情,

​ b: 设置token刷新,

​ c:设置TokenStore

​ d:Token 加强 ,令牌转换器

​ ④:允许post方式请求;

2.3 服务安全配置 ;check_token放行

AuthorizationServerConfig:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
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.EnableAuthorizationServer;
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.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

//授权服务配置
@Configuration
//开启授权服务配置
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //1.客户端详情配置(请求参数)
    @Autowired
    private DataSource dataSource ;

    @Autowired
    private PasswordEncoder passwordEncoder ;

    //1.1.注册客户端详情Bean,基于数据库,自动操作表:oauth_client_details
    @Bean
    public JdbcClientDetailsService jdbcClientDetailsService(){
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        //数据库的秘钥使用了PasswordEncoder加密
        jdbcClientDetailsService.setPasswordEncoder(passwordEncoder);
        return jdbcClientDetailsService;
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(jdbcClientDetailsService());
    }

    //2.授权服务端点配置(授权码,令牌)

    @Autowired
    private AuthenticationManager authenticationManager ;

    //2.1.定义授权码服务,连接数据库 oauth_code
    @Bean
    public JdbcAuthorizationCodeServices jdbcAuthorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }
    //2.2.令牌服务配置
    //令牌的管理服务
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        //创建默认的令牌服务
        DefaultTokenServices services = new DefaultTokenServices();
        //指定客户端详情配置
        services.setClientDetailsService(jdbcClientDetailsService());
        //支持产生刷新token
        services.setSupportRefreshToken(true);
        //token存储方式
        services.setTokenStore(tokenStore());

        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        services.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()

        return services;
    }

    //2.3.配置Token的存储方案
    //基于内存的Token存储
    @Bean
    public TokenStore tokenStore(){
        //return new InMemoryTokenStore();
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    //2.4.配置令牌转换器 ,设置JWT签名密钥。它可以是简单的MAC密钥,也可以是RSA密钥
    private final String sign_key  = "123";

    //JWT令牌校验工具
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设置JWT签名密钥。它可以是简单的MAC密钥,也可以是RSA密钥
        jwtAccessTokenConverter.setSigningKey(sign_key);
        return jwtAccessTokenConverter;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            //1.密码授权模式需要 密码模式,需要认证管理器
            .authenticationManager(authenticationManager)
            //2.授权码模式服务
            .authorizationCodeServices(jdbcAuthorizationCodeServices())
            //3.配置令牌管理服务
            .tokenServices(tokenService())
            //允许post方式请求
            .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    //2.授权服务安全配置(URL放行)
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //对应/oauth/check_token ,路径公开
                .checkTokenAccess("permitAll()")
                //允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }

}

SecurityConfig:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //密码加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权配置
        http.csrf().disable()   //屏蔽跨域防护
                .authorizeRequests()          //对请求做授权处理
                .antMatchers("/login").permitAll()  //登录路径放行
                // .antMatchers("/login.html").permitAll()//对登录页面跳转路径放行
                .anyRequest().authenticated() //其他路径都要拦截
                .and().formLogin()  //允许表单登录, 设置登陆页
                .successForwardUrl("/loginSuccess") // 设置登陆成功页(对应//controller),一定要有loginSuccess这个路径
                .and().logout().permitAll();    //登出
    }
    //配置认证管理器,授权模式为“poassword”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
Spring Authorization Server 中,可以通过自定义异常处理器来处理授权服务器中可能发生的异常,以提供更好的用户体验。 要自定义异常处理器,可以按照以下步骤进行: 1. 创建一个实现了 `org.springframework.security.oauth2.server.endpoint.OAuth2AuthorizationExceptionProblemHandler` 接口的异常处理器类,例如: ```java public class CustomAuthorizationExceptionProblemHandler implements OAuth2AuthorizationExceptionProblemHandler { @Override public ResponseEntity<OAuth2Error> handle(HttpServletRequest request, HttpServletResponse response, OAuth2Exception exception) throws IOException { // 自定义处理逻辑 return new ResponseEntity<>(new OAuth2Error("custom_error"), HttpStatus.BAD_REQUEST); } } ``` 2. 在 `AuthorizationServerEndpointsConfigurer` 中配置异常处理器,例如: ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.exceptionTranslator(new CustomOAuth2WebResponseExceptionTranslator()) .exceptionHandler(new CustomAuthorizationExceptionProblemHandler()); } // 其他配置... } ``` 在上面的示例中,`CustomAuthorizationExceptionProblemHandler` 类是自定义的异常处理器,它会在授权服务器发生异常时被调用,处理异常并返回自定义的错误响应。同时,还配置了一个 `CustomOAuth2WebResponseExceptionTranslator` 来处理异常。 需要注意的是,自定义的异常处理器和异常翻译器都需要实现 Spring Authorization Server 中对应的接口,并且在 `AuthorizationServerEndpointsConfigurer` 中进行配置。 另外,还可以通过实现 `org.springframework.web.servlet.HandlerExceptionResolver` 接口来对授权服务器中的异常进行全局处理,例如: ```java @RestControllerAdvice public class GlobalExceptionHandler implements HandlerExceptionResolver { @ResponseBody @ExceptionHandler(OAuth2AuthenticationException.class) public ResponseEntity<OAuth2Error> handleOAuth2AuthenticationException(OAuth2AuthenticationException ex) { // 自定义处理逻辑 return new ResponseEntity<>(new OAuth2Error("custom_error"), HttpStatus.BAD_REQUEST); } // 其他异常处理逻辑... } ``` 在上面的示例中,`GlobalExceptionHandler` 是一个全局异常处理器,它可以处理授权服务器中的所有异常,包括身份验证异常、访问令牌异常等。需要注意的是,全局异常处理器需要被声明为 `@RestControllerAdvice`,并实现 `HandlerExceptionResolver` 接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值