AuthorizationServer(授权服务器的简单搭建)

1.在pom文件里添加依赖

<!--  服务发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        

2.增加一个配置文件

spring:
  application:
    name: authorization-server
  cloud:
    nacos:
      discovery:
        server-addr: nacos-server:8848
server:
  port: 9999

3.创建启动类

@SpringBootApplication
public class AuthorizationApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthorizationApplication.class, args);
    }
}

4.增加配置类

4.1 授权服务器的配置

package com.bjsxt.config;
@EnableAuthorizationServer//开启授权服务功能
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
/**
 * 添加第三方客户端
 *
 */
    @Override
    //输入config会自动弹出来configure的方法,这里注意要选择的是参数是client的
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("coin-api")//第三方客户端的名称
                .secret(passwordEncoder.encode("coin-secret"))//第三方客户端的密钥
                .scopes("all")//第三方客户端的授权范围
                .accessTokenValiditySeconds(3600)//token的有效期
                .refreshTokenValiditySeconds(7*3600);//redresh_token的有效期
        super.configure(clients);
    }
/**
 * 配置验证管理器,UserdetailService
 */
    @Override
    //同样这里的configure方法也要注意选择的是endpoint
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
        super.configure(endpoints);
    }
}

4.2 web安全的配置

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 注入一个验证管理器
     *
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 资源的放行
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); // 关闭scrf
        http.authorizeRequests().anyRequest().authenticated();
        //注意这里删除了super类,防止服务启动的时候冲突报错,
    }


    /**
     * 创建一个测试的UserDetail
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService() {
        //InMemoryUserDetailsManager是Spring Security Config提供的一个安全配置器
        //安全构建器提供的是一个基于内存存储用户账号详情的用户账号详情管理对象
        //主要应用于开发调试环境,其设计目的主要是测试和功能演示,一般不在生产环境中使用。
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        //注意这里导入的user的包是org.springframework.security.core.userdetails.User;
        User user = new User("admin", "123456", Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"))) ;
        inMemoryUserDetailsManager.createUser(user);
        return inMemoryUserDetailsManager;
    }

    /**
     * 注入密码的验证管理器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
    //注意这个不加密的方法已经废弃掉了,我们这里仅仅用来测试
        return NoOpPasswordEncoder.getInstance();
    }
}

5.利用postman工具进行测试

5.1 postman下载安装

若本机已经安装postman,则此步骤忽略
下载地址postman
傻瓜式安装

5.2

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 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、付费专栏及课程。

余额充值