当前位置: 首页 > news >正文

湖南省网站建设_网站建设公司_Logo设计_seo优化

dede静态网站模板下载,全国企业信息网查询平台官网,广西建设厅网站培训中心,东莞网站建设服务目录 前言1、自定义认证对象2、自定义TokenGranter3、自定义AuthenticationProvider4、配置自定义AuthenticationProvider、自定义TokenGranter5、配置客户端授权模式6、测试 前言 在Oauth2中#xff0c;提供了几种基本的认证模式#xff0c;有密码模式、客户端模式、授权码… 目录 前言1、自定义认证对象2、自定义TokenGranter3、自定义AuthenticationProvider4、配置自定义AuthenticationProvider、自定义TokenGranter5、配置客户端授权模式6、测试 前言 在Oauth2中提供了几种基本的认证模式有密码模式、客户端模式、授权码模式和简易模式。但很多时候我们有自己的认证授权逻辑比如手机验证码等这就需要我们自定义认证授权模式 在看该文章之前最好先看下面这个文章先了解下Spring Security Oauth2的授权认证流程 一文弄懂Spring Security oauth2授权认证流程 下面我就以手机验证码为例自定义一个授权模式 1、自定义认证对象 我们的认证对象是通过Authentication对象进行传递的Authentication只是一个接口它的基类是AbstractAuthenticationToken抽象类AbstractAuthenticationToken是Spring Security中用于表示身份验证令牌的抽象类。一般我们自定义认证对象都是继承自AbstractAuthenticationToken AbstractAuthenticationToken类的主要属性包括 principal表示认证主体通常是用户对象UserDetails。 credentials存储了与主体关联的认证信息例如密码。 authorities表示主体所拥有的权限集合。 authenticated表示是否已经通过认证true为已认证false为未认证 details用于存储与认证令牌相关的附加信息。该属性的类型是Object因此可以存储任何类型的数据。 例如在基于表单的认证中可以将表单提交的用户名和密码存储在credentials属性中并将其他与认证相关的详细信息例如用户名和密码的来源、表单提交的IP地址等存储在details属性中。下面是我自定义的一个认证对象类 Getter Setter public class PhoneAuthenticationToken extends AbstractAuthenticationToken {private final Object principal;private Object credentials;/*** 可以自定义属性*/private String phone;/*** 创建一个未认证的对象* param principal* param credentials*/public PhoneAuthenticationToken(Object principal, Object credentials) {super(null);this.principal principal;this.credentials credentials;setAuthenticated(false);}/*** 创建一个已认证对象* param authorities* param principal* param credentials*/public PhoneAuthenticationToken(Collection? extends GrantedAuthority authorities, Object principal, Object credentials) {super(authorities);this.principal principal;this.credentials credentials;// 必须使用super因为我们要重写super.setAuthenticated(true);}/*** 不能暴露Authenticated的设置方法防止直接设置* param isAuthenticated* throws IllegalArgumentException*/Overridepublic void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {Assert.isTrue(!isAuthenticated,Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead);super.setAuthenticated(false);}/*** 用户凭证如密码* return*/Overridepublic Object getCredentials() {return credentials;}/*** 被认证主体的身份如果是用户名/密码登录就是用户名* return*/Overridepublic Object getPrincipal() {return principal;} } 2、自定义TokenGranter TokenGranter是我们授权模式接口而它的基类是AbstractTokenGranter抽象类通过继承AbstractTokenGranter类并实现其抽象方法就可以实现我们自定义的授权模式了 下面我参考ResourceOwnerPasswordTokenGranter来实现我们的手机验证码授权模式 /*** 手机验证码授权模式*/ public class PhoneCodeTokenGranter extends AbstractTokenGranter {//授权类型名称private static final String GRANT_TYPE phonecode;private final AuthenticationManager authenticationManager;/*** 构造函数* param tokenServices* param clientDetailsService* param requestFactory* param authenticationManager*/public PhoneCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {this(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE,authenticationManager);}public PhoneCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType, AuthenticationManager authenticationManager) {super(tokenServices, clientDetailsService, requestFactory, grantType);this.authenticationManager authenticationManager;}Overrideprotected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {MapString, String parameters new LinkedHashMapString, String(tokenRequest.getRequestParameters());//获取参数String phone parameters.get(phone);String phonecode parameters.get(phonecode);//创建未认证对象Authentication userAuth new PhoneAuthenticationToken(phone, phonecode);((AbstractAuthenticationToken) userAuth).setDetails(parameters);try {//进行身份认证userAuth authenticationManager.authenticate(userAuth);}catch (AccountStatusException ase) {//将过期、锁定、禁用的异常统一转换throw new InvalidGrantException(ase.getMessage());}catch (BadCredentialsException e) {// 用户名/密码错误我们应该发送400/invalid grantthrow new InvalidGrantException(e.getMessage());}if (userAuth null || !userAuth.isAuthenticated()) {throw new InvalidGrantException(用户认证失败: phone);}OAuth2Request storedOAuth2Request getRequestFactory().createOAuth2Request(client, tokenRequest);return new OAuth2Authentication(storedOAuth2Request, userAuth);} } Spring Security Oauth2会根据传入的grant_type来将请求转发到对应的Granter进行处理。而用户信息合法性的校验是交给authenticationManager处理的 authenticationManager不直接进行认证而是通过委托模式将认证任务委托给AuthenticationProvider接口的实现类来完成一个AuthenticationProvider就对应一个认证方式 3、自定义AuthenticationProvider 因为身份认证是由AuthenticationProvider实现的所以我们还需要实现一个自定义AuthenticationProvider 如果AuthenticationProvider认证成功它会返回一个完全有效的Authentication对象其中authenticated属性为true已授权的权限列表GrantedAuthority列表以及用户凭证如果认证失败一般AuthenticationProvider会抛出AuthenticationException异常。 /*** 手机验证码认证授权提供者*/ Data public class PhoneAuthenticationProvider implements AuthenticationProvider {private RedisTemplateString,Object redisTemplate;private PhoneUserDetailsService phoneUserDetailsService;public static final String PHONE_CODE_SUFFIX phone:code:;Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {//先将authentication转为我们自定义的Authentication对象PhoneAuthenticationToken authenticationToken (PhoneAuthenticationToken) authentication;//校验参数Object principal authentication.getPrincipal();Object credentials authentication.getCredentials();if (principal null || .equals(principal.toString()) || credentials null || .equals(credentials.toString())){throw new InternalAuthenticationServiceException(手机/手机验证码为空);}//获取手机号和验证码String phone (String) authenticationToken.getPrincipal();String code (String) authenticationToken.getCredentials();//查找手机用户信息验证用户是否存在UserDetails userDetails phoneUserDetailsService.loadUserByUsername(phone);if (userDetails null){throw new InternalAuthenticationServiceException(用户手机不存在);}String codeKey PHONE_CODE_SUFFIXphone;//手机用户存在验证手机验证码是否正确if (!redisTemplate.hasKey(codeKey)){throw new InternalAuthenticationServiceException(验证码不存在或已失效);}String realCode (String) redisTemplate.opsForValue().get(codeKey);if (StringUtils.isBlank(realCode) || !realCode.equals(code)){throw new InternalAuthenticationServiceException(验证码错误);}//返回认证成功的对象PhoneAuthenticationToken phoneAuthenticationToken new PhoneAuthenticationToken(userDetails.getAuthorities(),phone,code);phoneAuthenticationToken.setPhone(phone);//details是一个泛型属性用于存储关于认证令牌的额外信息。其类型是 Object所以你可以存储任何类型的数据。这个属性通常用于存储与认证相关的详细信息比如用户的角色、IP地址、时间戳等。phoneAuthenticationToken.setDetails(userDetails);return phoneAuthenticationToken;}/*** ProviderManager 选择具体Provider时根据此方法判断* 判断 authentication 是不是 SmsCodeAuthenticationToken 的子类或子接口*/Overridepublic boolean supports(Class? authentication) {//isAssignableFrom方法如果比较类和被比较类类型相同或者是其子类、实现类返回truereturn PhoneAuthenticationToken.class.isAssignableFrom(authentication);}}4、配置自定义AuthenticationProvider、自定义TokenGranter 自定义AuthenticationProvider需要在WebSecurityConfigurerAdapter 配置类进行配置 Configuration EnableWebSecurity public class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter {Autowiredprivate PasswordEncoder passwordEncoder;Autowiredprivate RedisTemplateString, Object redisTemplate;Autowiredprivate PhoneUserDetailsService phoneUserDetailsService;Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//创建一个登录用户auth.inMemoryAuthentication().withUser(admin).password(passwordEncoder.encode(123123)).authorities(admin_role);//添加自定义认证提供者auth.authenticationProvider(phoneAuthenticationProvider());}/*** 手机验证码登录的认证提供者* return*/Beanpublic PhoneAuthenticationProvider phoneAuthenticationProvider(){//实例化provider把需要的属性set进去PhoneAuthenticationProvider phoneAuthenticationProvider new PhoneAuthenticationProvider();phoneAuthenticationProvider.setRedisTemplate(redisTemplate);phoneAuthenticationProvider.setPhoneUserDetailsService(phoneUserDetailsService);return phoneAuthenticationProvider;}...省略其他配置 } 自定义Granter配置需要在AuthorizationServerConfigurerAdapter配置类进行配置 Configuration EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {AutowiredAuthenticationManager authenticationManager;/*** 密码模式需要注入authenticationManager* param endpoints*/Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {// 获取原有默认授权模式(授权码模式、密码模式、客户端模式、简化模式)的授权者用于支持原有授权模式ListTokenGranter granterList new ArrayList(Collections.singletonList(endpoints.getTokenGranter()));//添加我们的自定义TokenGranter到集合granterList.add(new PhoneCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),endpoints.getOAuth2RequestFactory(), authenticationManager));//CompositeTokenGranter是一个TokenGranter组合类CompositeTokenGranter compositeTokenGranter new CompositeTokenGranter(granterList);endpoints.authenticationManager(authenticationManager).tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter()).tokenGranter(compositeTokenGranter)//将组合类设置进AuthorizationServerEndpointsConfigurer;}...省略其他配置 } 主要将原有授权模式类和自定义授权模式类添加到一个集合然后用该集合为入参创建一个CompositeTokenGranter组合类最后在tokenGranter设置CompositeTokenGranter进去 CompositeTokenGranter是一个组合类它可以将多个TokenGranter实现组合起来以便在处理OAuth2令牌授权请求时使用。 5、配置客户端授权模式 最后我们还需要在AuthorizationServerConfigurerAdapter配置类的configure(ClientDetailsServiceConfigurer clients)方法中配置客户端信息在客户端支持的授权模式中添加上我们自定义的授权模式即phonecode Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient(admin).authorizedGrantTypes(authorization_code, password, implicit,client_credentials,refresh_token,phonecode)...省略其他配置}6、测试 在postman使用手机验证码授权模式获取token 可以看到我们已经成功使用手机验证码获取token
http://www.ihoyoo.com/news/139478.html

相关文章:

  • 城乡建设官方网站汉中建设工程招标信息网
  • 做兼职用什么网站最好网站建设步骤列表图片
  • wordpress分站域名备案需要多少时间
  • 网上书店网站建设实训报告总结网站后台任务
  • 做网站服务器价格多少合适北京工商注册查询系统官网
  • 当今弹幕网站建设情况株洲网站建设工作室
  • 中国工程建设监理网站互动营销名词解释
  • 苏州企业名称大全青岛seo推广专员
  • php网站开发实例电子版商标设计网址大全
  • 怎么用vs2010做网站设计网站维护中页面
  • 企业网站改版项目描述无极小说网
  • 做京东网站的摘要给一个网站
  • 网站关键词如何做竞价大通拓客软件官网
  • 专业做网站上海网站建设包括哪些方面
  • 网站推广品牌艺术生搭建wordpress个人博客
  • 网站色彩的搭配原则有哪些一定要知道的网站
  • 安庆什么网站好小事做什么是网络营销的综合性工具
  • 做盗版小说网站哈尔滨网站建设丿薇
  • 百度移动网站建设有几种百度不到公司网站
  • 广州建网站的公司做门户网站需要注册公司吗
  • 哪个网站可以领手工回家做财务公司是做什么的
  • 深圳网站建设服务清单沈阳专业的网站设计公司
  • 全国物流网站网站标签中的图片怎么做的
  • 荣耀手机商城官方网站入口推广公司业务
  • 中国建设银行网站许昌seo推广
  • 公司做网站的原因网站建设商
  • 什么是网站版式不需要充值的传奇手游
  • 给别人做网站别人违法经营6湘潭市建设路学校网站
  • ai生成建筑网站江苏省建设局报考网站
  • 网站建设应遵循的原则比较有名的公司网站