欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-08 16:28:19
一 认证中心搭建添加依赖,如果使用spring cloud的话,不管哪个服务都只需要这一个封装好的依赖即可 org.spri...

一 认证中心搭建

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

<dependency>
      <groupid>org.springframework.cloud</groupid>
      <artifactid>spring-cloud-starter-oauth2</artifactid>
    </dependency>

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

配置oauth2认证中心

/**
 * 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");
        /*redirecturis 关于这个配置项,是在 oauth2协议中,认证成功后的回调地址,此值同样可以配置多个*/
     //数据库配置,需要建表
//    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:
 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

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

使用token

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

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