栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

一 认证中心搭建

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


      org.springframework.cloud
      spring-cloud-starter-oauth2
    

配置spring 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();
  }
}

配置OAuth2认证中心


@EnableAuthorizationServer //声明OAuth2认证中心
@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");
 
     //数据库配置,需要建表
//    clients.withClientDetails(clientDetailsService());
//    clients.jdbc(dataSource);
  }
  // 声明 ClientDetails实现
  private ClientDetailsService clientDetailsService() {
    return new JdbcClientDetailsService(dataSource);
  }

  
  @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_这两个

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

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

security:
 oauth2:
  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

使用token

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/130459.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号