热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

基于SpringBoot整合oauth2实现token认证

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

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

session和token的区别:

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

Oauth2 密码授权流程

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

1. pom


    
      org.springframework.boot
      spring-boot-starter-security
    
    
      org.springframework.security.oauth
      spring-security-oauth2
    

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 {
    Mapmap = 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、测试

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


推荐阅读
  • HDIV简介一个简单又强大的安全框架
    为什么80%的码农都做不了架构师?惯例官方纯英文档:https:hdivsecurity.comtechnical-documentationdo ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了markdown[软件代理设置]相关的知识,希望对你有一定的参考价值。 ... [详细]
  • DockerDataCenter系列(四)-离线安装UCP和DTR,Go语言社区,Golang程序员人脉社 ... [详细]
  • 弹性云服务器ECS弹性云服务器(ElasticCloudServer)是一种可随时自助获取、可弹性伸缩的云服务器,帮助用户打造可靠、安全、灵活、高效的应用环境 ... [详细]
  • 这座城市多了十只伤心的鸽
    这个作业属于哪个课程2021春软件工程实践|W班(福州大学)这个作业要求在哪里团队第四次作业这个作业的目标设计项目原型、制作项目需求规格说明书团队名称这座城市多了十只伤心的鸽其他参 ... [详细]
  • 前端跨域访问后端数据的方法
    参考链接:https:mp.weixin.qq.coms4G_27oRLSMMYBFvtYZgqcg一、什么是跨域当两个域名的协议、子域名、主域名、端口号中有任意一个不 ... [详细]
  • 深入浅出JWT
    JWT(JSONWEBTOKEN)的组成https:jwt.ioheader(头部)承载两部分信息:声明 ... [详细]
  • 背景应用安全领域,各类攻击长久以来都危害着互联网上的应用,在web应用安全风险中,各类注入、跨站等攻击仍然占据着较前的位置。WAF(Web应用防火墙)正是为防御和阻断这类攻击而存在 ... [详细]
  • 本文介绍了互联网思维中的三个段子,涵盖了餐饮行业、淘品牌和创业企业的案例。通过这些案例,探讨了互联网思维的九大分类和十九条法则。其中包括雕爷牛腩餐厅的成功经验,三只松鼠淘品牌的包装策略以及一家创业企业的销售额增长情况。这些案例展示了互联网思维在不同领域的应用和成功之道。 ... [详细]
  • GSIOpenSSH PAM_USER 安全绕过漏洞
    漏洞名称:GSI-OpenSSHPAM_USER安全绕过漏洞CNNVD编号:CNNVD-201304-097发布时间:2013-04-09 ... [详细]
  • C#设计模式之八装饰模式(Decorator Pattern)【结构型】
    一、引言今天我们要讲【结构型】设计模式的第三个模式,该模式是【装饰模式】,英文名称:DecoratorPattern。我第一次看到这个名称想到的是另外一个词语“装修”,我就说说我对“装修”的理 ... [详细]
  • 浅解XXE与Portswigger Web Sec
    XXE与PortswiggerWebSec​相关链接:​博客园​安全脉搏​FreeBuf​XML的全称为XML外部实体注入,在学习的过程中发现有回显的XXE并不多,而 ... [详细]
  • 详解 Python 的二元算术运算,为什么说减法只是语法糖?[Python常见问题]
    原题|UnravellingbinaryarithmeticoperationsinPython作者|BrettCannon译者|豌豆花下猫(“Python猫 ... [详细]
author-avatar
chnger
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有