当前位置:   article > 正文

SpringCloud OAuth2 + JWT 认证授权(一)授权服务器_keystorekeyfactory

keystorekeyfactory

系列文章

Spring Cloud oAuth2(一)搭建授权服务器以及访问

Spring Cloud oAuth2(二)搭建资源服务器以及测试

SpringCloud OAuth2 + JWT 认证授权(一)授权服务器

SpringCloud OAuth2 + JWT 认证授权(二)资源服务器

目录

简介

实体对象

授权配置

结尾


简介

这里对个人在搭建第三方授权服务的过程中,遇到的问题进行总结。如果不是非必要的第三方登录,单个JWT就能满足简单的授权验证的,不过相关的验证和授权需要自己去写。本文源码:源码地址

实体对象

  • 角色
  1. @Data
  2. @Entity
  3. public class Role implements GrantedAuthority, Serializable {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;
  7. @Column(nullable = false,unique = true)
  8. private String name;
  9. @Override
  10. public String getAuthority() {
  11. return name;
  12. }
  13. }
  • 用户以及和角色的对应关系
  1. @Data
  2. @Entity
  3. public class User implements UserDetails, Serializable {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;
  7. @Column(nullable = false,unique = true)
  8. private String username;
  9. private String password;
  10. @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
  11. @JoinTable(
  12. name = "user_role",
  13. joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "id")},
  14. inverseJoinColumns = {@JoinColumn(name="role_id",referencedColumnName = "id")}
  15. )
  16. List<Role> authorities;
  17. @Override
  18. public Collection<? extends GrantedAuthority> getAuthorities() {
  19. return authorities;
  20. }
  21. @Override
  22. public boolean isAccountNonExpired() {
  23. return true;
  24. }
  25. @Override
  26. public boolean isAccountNonLocked() {
  27. return true;
  28. }
  29. @Override
  30. public boolean isCredentialsNonExpired() {
  31. return true;
  32. }
  33. @Override
  34. public boolean isEnabled() {
  35. return true;
  36. }

注意:对象相关的角色信息一定要返回(authorities),这里本人写快了返回null。。。。

授权配置

  • 实现简单的查询接口
  1. public interface UserDao extends JpaRepository<User,Long> {
  2. User findUserByUsername(String username);
  3. }
  • 实现UserDetailsService并重写loadUserByUsername方法
  1. @Service
  2. public class UserService implements UserDetailsService {
  3. @Autowired
  4. private UserDao userDao;
  5. @Override
  6. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  7. return userDao.findUserByUsername(username);
  8. }
  9. }
  • 重写spring security相关配置,配置授权验证方式等
  1. @Configuration
  2. @EnableWebSecurity
  3. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  4. @Autowired
  5. private UserService userService;
  6. @Bean
  7. public PasswordEncoder passwordEncoder()
  8. {
  9. return new BCryptPasswordEncoder();
  10. }
  11. //相关http安全配置,异常处理和相关资源以及用户授权配置
  12. @Override
  13. protected void configure(HttpSecurity http) throws Exception {
  14. http
  15. .csrf().disable()
  16. .exceptionHandling()
  17. .authenticationEntryPoint((request,response,authException)->response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
  18. .and()
  19. .authorizeRequests()
  20. .anyRequest()
  21. .authenticated()
  22. .and()
  23. .httpBasic();
  24. }
  25. //用户读取位置以及密码验证方式
  26. @Override
  27. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  28. auth
  29. .userDetailsService(userService)
  30. .passwordEncoder(passwordEncoder());
  31. }
  32. //开启密码验证
  33. @Bean
  34. @Override
  35. public AuthenticationManager authenticationManagerBean() throws Exception {
  36. return super.authenticationManagerBean();
  37. }
  38. }
  • 授权服务器授权配置
  1. @Configuration
  2. @EnableAuthorizationServer
  3. public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
  4. @Autowired
  5. @Qualifier("authenticationManagerBean")
  6. public AuthenticationManager authenticationManager;
  7. @Autowired
  8. private PasswordEncoder passwordEncoder;
  9. @Override
  10. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  11. clients
  12. .inMemory()
  13. .withClient("kevin")
  14. .secret(passwordEncoder.encode("kevin12345"))
  15. .scopes("client")
  16. .authorizedGrantTypes("password","refresh_token")
  17. .accessTokenValiditySeconds(3600);
  18. }
  19. @Override
  20. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  21. endpoints
  22. //存储策略
  23. .tokenStore(new JwtTokenStore(jwtTokenEnhancer()))
  24. //增强策略
  25. .tokenEnhancer(jwtTokenEnhancer())
  26. //开启密码授权验证
  27. .authenticationManager(authenticationManager);
  28. }
  29. //jwt身份转换器,用于将封装在jwt里面的信息解析或者转换
  30. public JwtAccessTokenConverter jwtTokenEnhancer()
  31. {
  32. //RSA非对称加密密钥工厂,参数一为密钥地址,参数二为打开密钥的密码
  33. KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("auth-jwt.jks"),"jwt12345".toCharArray());
  34. JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
  35. converter.setKeyPair(keyStoreKeyFactory.getKeyPair("auth-jwt","jwt12345".toCharArray()));
  36. return converter;
  37. }
  38. @Override
  39. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  40. security
  41. .tokenKeyAccess("permitAll()")
  42. .checkTokenAccess("permitAll()")
  43. .allowFormAuthenticationForClients();
  44. }

注意:

  1. 这里的查看密钥storepass和生成密钥keypass是一样的,相关的RSA私钥和公钥生成博客有很多
  2. 要用openssl导出公钥命令的必须下载安装openssl服务
  3. 公钥导出可以直接复制显示的publickey(不用缩成一行!)并提取成文件(文中是这样的),也可以写程序去获取

结尾

这里仅仅是简单的demo,生产用还有很多不足的地方,比如退出token失效等。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/505671
推荐阅读
相关标签
  

闽ICP备14008679号