当前位置: 移动技术网 > IT编程>开发语言>Java > 基于SpringBoot整合oauth2实现token认证

基于SpringBoot整合oauth2实现token认证

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了基于springboot整合oauth2实现token 认证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

session和token的区别:

  • session是空间换时间,而token是时间换空间。session占用空间,但是可以管理过期时间,token管理部了过期时间,但是不占用空间.
  • sessionid失效问题和token内包含。
  • session基于cookie,app请求并没有cookie 。
  • token更加安全(每次请求都需要带上)

oauth2 密码授权流程

在oauth2协议里,每一个应用都有自己的一个clientid和clientsecret(需要去认证方申请),所以一旦想通过认证,必须要有认证方下发的clientid和secret。

1. pom

<!--security-->
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-security</artifactid>
    </dependency>
    <dependency>
      <groupid>org.springframework.security.oauth</groupid>
      <artifactid>spring-security-oauth2</artifactid>
    </dependency>

2. userdetail实现认证第一步

myuserdetailsservice.java

@autowired
  private passwordencoder passwordencoder;

  /**
   * 根据进行登录
   * @param username
   * @return
   * @throws usernamenotfoundexception
   */
  @override
  public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
    log.info("登录用户名:"+username);
    string password = passwordencoder.encode("123456");
    //user三个参数  (用户名+密码+权限)
    //根据查找到的用户信息判断用户是否被冻结
    log.info("数据库密码:"+password);
    return new user(username,password, authorityutils.commaseparatedstringtoauthoritylist("admin"));
  }

3. 获取token的控制器

@restcontroller
public class oauthcontroller {

  @autowired
  private clientdetailsservice clientdetailsservice;
  @autowired
  private authorizationservertokenservices authorizationservertokenservices;
  @autowired
  private authenticationmanager authenticationmanager;

  @postmapping("/oauth/gettoken")
  public object gettoken(@requestparam string username, @requestparam string password, httpservletrequest request) throws ioexception {
    map<string,object>map = new hashmap<>(8);
    //进行验证
    string header = request.getheader("authorization");
    if (header == null && !header.startswith("basic")) {
      map.put("code",500);
      map.put("message","请求投中无client信息");
      return map;
    }
    string[] tokens = this.extractanddecodeheader(header, request);
    assert tokens.length == 2;
    //获取clientid 和 clientsecret
    string clientid = tokens[0];
    string clientsecret = tokens[1];
    //获取 clientdetails
    clientdetails clientdetails = clientdetailsservice.loadclientbyclientid(clientid);
    if (clientdetails == null){
      map.put("code",500);
      map.put("message","clientid 不存在"+clientid);
      return map;
      //判断 方言 是否一致
    }else if (!stringutils.equals(clientdetails.getclientsecret(),clientsecret)){
      map.put("code",500);
      map.put("message","clientsecret 不匹配"+clientid);
      return map;
    }
    //使用username、密码进行登录
    usernamepasswordauthenticationtoken authentication = new usernamepasswordauthenticationtoken(username, password);
    //调用指定的userdetailsservice,进行用户名密码验证
    authentication authenticate = authenticationmanager.authenticate(authentication);
    hrutils.setcurrentuser(authenticate);
    //放到session中
    //密码授权 模式, 组建 authentication
    tokenrequest tokenrequest = new tokenrequest(new hashmap<>(),clientid,clientdetails.getscope(),"password");

    oauth2request oauth2request = tokenrequest.createoauth2request(clientdetails);
    oauth2authentication oauth2authentication = new oauth2authentication(oauth2request,authentication);

    oauth2accesstoken token = authorizationservertokenservices.createaccesstoken(oauth2authentication);
    map.put("code",200);
    map.put("token",token.getvalue());
    map.put("refreshtoken",token.getrefreshtoken());
    return map;
  }

  /**
   * 解码请求头
   */
  private string[] extractanddecodeheader(string header, httpservletrequest request) throws ioexception {
    byte[] base64token = header.substring(6).getbytes("utf-8");

    byte[] decoded;
    try {
      decoded = base64.decode(base64token);
    } catch (illegalargumentexception var7) {
      throw new badcredentialsexception("failed to decode basic authentication token");
    }

    string token = new string(decoded, "utf-8");
    int delim = token.indexof(":");
    if (delim == -1) {
      throw new badcredentialsexception("invalid basic authentication token");
    } else {
      return new string[]{token.substring(0, delim), token.substring(delim + 1)};
    }
  }
}

4. 核心配置

(1)、security 配置类 说明登录方式、登录页面、哪个url需要认证、注入登录失败/成功过滤器

@configuration
public class browsersecurityconfig extends websecurityconfigureradapter {

  /**
   * 注入 自定义的 登录成功处理类
   */
  @autowired
  private myauthenticationsuccesshandler mysuccesshandler;
  /**
   * 注入 自定义的 登录失败处理类
   */
  @autowired
  private myauthenticationfailhandler myfailhandler;

  @autowired
  private validatecodefilter validatecodefilter;

  /**
   * 重写passwordencoder 接口中的方法,实例化加密策略
   * @return 返回 bcrypt 加密策略
   */
  @bean
  public passwordencoder passwordencoder(){
    return new bcryptpasswordencoder();
  }

  @override
  protected void configure(httpsecurity http) throws exception {
    //在usernamepasswordauthenticationfilter 过滤器前 加一个过滤器 来搞验证码
    http.addfilterbefore(validatecodefilter, usernamepasswordauthenticationfilter.class)
        //表单登录 方式
        .formlogin()
        .loginpage("/authentication/require")
        //登录需要经过的url请求
        .loginprocessingurl("/authentication/form")
        .passwordparameter("pwd")
        .usernameparameter("user")
        .successhandler(mysuccesshandler)
        .failurehandler(myfailhandler)
        .and()
        //请求授权
        .authorizerequests()
        //不需要权限认证的url
        .antmatchers("/oauth/*","/authentication/*","/code/image").permitall()
        //任何请求
        .anyrequest()
        //需要身份认证
        .authenticated()
        .and()
        //关闭跨站请求防护
        .csrf().disable();
    //默认注销地址:/logout
    http.logout().
        //注销之后 跳转的页面
        logoutsuccessurl("/authentication/require");
  }

  /**
   * 认证管理
   *
   * @return 认证管理对象
   * @throws exception 认证异常信息
   */
  @override
  @bean
  public authenticationmanager authenticationmanagerbean() throws exception {
    return super.authenticationmanagerbean();
  }
}

(2)、认证服务器

@configuration
@enableauthorizationserver
public class myauthorizationserverconfig extends authorizationserverconfigureradapter {
  @autowired
  private authenticationmanager authenticationmanager;

  @autowired
  private myuserdetailsservice userdetailsservice;




  @override
  public void configure(authorizationserversecurityconfigurer security) throws exception {
    super.configure(security);
  }

  /**
   * 客户端配置(给谁发令牌)
   * @param clients
   * @throws exception
   */
  @override
  public void configure(clientdetailsserviceconfigurer clients) throws exception {
    clients.inmemory().withclient("internet_plus")
        .secret("internet_plus")
        //有效时间 2小时
        .accesstokenvalidityseconds(72000)
        //密码授权模式和刷新令牌
        .authorizedgranttypes("refresh_token","password")
        .scopes( "all");
  }

  @override
  public void configure(authorizationserverendpointsconfigurer endpoints) throws exception {
    endpoints
        .authenticationmanager(authenticationmanager)
        .userdetailsservice(userdetailsservice);
  }
}

@enableresourceserver这个注解就决定了这是个资源服务器。它决定了哪些资源需要什么样的权限。

5、测试

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网