认证资源中心如何使用Spring cloud oauth2搭建
创始人
2024-11-19 14:01:31
0次

一 认证中心搭建

添加依赖,如果使用spring cloud的话,不管哪个服务都只需要这一个封装好的依赖即可


      org.springframework.cloud
      spring-cloud-starter-oauth3
    

配置spring security

/**
 * security配置类
 */
@Configuration
@EnableWebSecurity //开启web保护
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法注解权限配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Qualifier("userDetailsServiceImpl")
  @Autowired
  private UserDetailsService userDetailsService;

  //配置用户签名服务,赋予用户权限等
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService)//指定userDetailsService实现类去对应方法认
        .passwordEncoder(passwordEncoder()); //指定密码加密器
  }
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
  //配置拦截保护请求,什么请求放行,什么请求需要验证
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        //配置所有请求开启认证
        .anyRequest().permitAll()
        .and().httpBasic(); //启用http基础验证
  }

  // 配置token验证管理的Bean
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

配置OAuth3认证中心

/**
 * OAuth3授权服务器
 */
@EnableAuthorizationServer //声明OAuth3认证中心
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  @Autowired
  @Qualifier("authenticationManagerBean")
  private AuthenticationManager authenticationManager;
  @Autowired
  private DataSource dataSource;
  @Autowired
  private UserDetailsService userDetailsService;
  @Autowired
  private PasswordEncoder passwordEncoder;
  /**
   * 这个方法主要是用于校验注册的第三方客户端的信息,可以存储在数据库中,默认方式是存储在内存中,如下所示,注释掉的代码即为内存中存储的方式
   */
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
        clients.inMemory()
        .withClient("hou") // 客户端id,必须有
        .secret(passwordEncoder.encode("123456")) // 客户端密码
            .scopes("server")
        .authorizedGrantTypes("authorization_code", "password", "refresh_token") //验证类型
        .redirectUris("http://www.baidu.com");
        /*redirectUris 关于这个配置项,是在 OAuth3协议中,认证成功后的回调地址,此值同样可以配置多个*/
     //数据库配置,需要建表
//    clients.withClientDetails(clientDetailsService());
//    clients.jdbc(dataSource);
  }
  // 声明 ClientDetails实现
  private ClientDetailsService clientDetailsService() {
    return new JdbcClientDetailsService(dataSource);
  }

  /**
   * 控制token端点信息
   */
  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
        .tokenStore(tokenStore())
        .userDetailsService(userDetailsService);
  }
  //获取token存储类型
  @Bean
  public TokenStore tokenStore() {
    //return new JdbcTokenStore(dataSource); //存储mysql中
    return new InMemoryTokenStore();  //存储内存中
    //new RedisTokenStore(connectionFactory); //存储redis中
  }

  //配置获取token策略和检查策略
  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.tokenKeyAccess("permitAll()") //获取token请求不进行拦截
        .checkTokenAccess("isAuthenticated()") //验证通过返回token信息
        .allowFormAuthenticationForClients();  // 允许 客户端使用client_id和client_secret获取token
  }
}

二 测试获取Token

默认获取token接口图中2所示,这里要说明一点,参数key千万不能有空格,尤其是client_这两个

认证资源中心如何使用Spring cloud oauth2搭建

三 需要保护的资源服务配置

yml配置客户端信息以及认中心地址

security:
 oauth3:
  resource:
   tokenInfoUri: http://localhost:9099/oauth/check_token
   preferTokenInfo: true
  client:
   client-id: hou
   client-secret: 123456
   grant-type: password
   scope: server
   access-token-uri: http://localhost:9099/oauth/token

配置认证中心地址即可

/**
 * 资源中心配置
 */
@Configuration
@EnableResourceServer // 声明资源服务,即可开启token验证保护
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法权限注解
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        //配置所有请求不需要认证,在方法用注解定制权限
        .anyRequest().permitAll();
  }
}

编写权限控制

@RestController
@RequestMapping("test")
public class TestController {
  //不需要权限
  @GetMapping("/hou")
  public String test01(){
    return "返回测试数据hou";
  }
  @PreAuthorize("hasAnyAuthority('ROLE_USER')") //需要权限
  @GetMapping("/zheng")
  public String test02(){
    return "返回测试数据zheng";
  }
}

四 测试权限

不使用token

认证资源中心如何使用Spring cloud oauth2搭建

使用token

认证资源中心如何使用Spring cloud oauth2搭建

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...