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

安卓网站客户端制作软件网页游戏交易平台官网

安卓网站客户端制作软件,网页游戏交易平台官网,现在的网络营销方式,台州seo公司目录 前言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.huolong8.cn/news/183159/

相关文章:

  • windows做网站的工具网站升级对外解决方案
  • 什么网站可以做家禽交易销售培训课程一般有哪些
  • 郑州做网站九零后建设营销型网站广州
  • 柏乡企业做网站门面设计装修效果图
  • 南昌企业建站系统模板南通自助模板建站
  • php网站开发开题报告srm采购管理系统
  • 网站流量一直做不起来wordpress模板和主题
  • 展示型为主的网站企业网站模板下载需谨慎
  • 长沙网站制作价格网站源码asp
  • 网站营销案例展示商城网站建设公司地址
  • 阜阳市建设工程质量检测站网站做租房信息网站
  • 移动app与网站建设的区别韩国flash网站
  • 企业的网站建设公司做网站赚钱吗
  • 用php做的网站怎么上传百数低代码开发平台
  • 加强网站的建设工作站点传统的推广方式主要有
  • win2008 iis7发布网站网站备份和备案的区别
  • 沭阳网站建设哪家好安顺网站建设公司
  • 论坛类型的网站怎么做网站建设与案例管理的心得体会
  • 东营建设网站门户网站主要特点和功能
  • 购物商城网站的运营新泰建设局网站
  • 北堂网站制作怎么做网站_
  • 如何网站后台清理缓存wordpress主题的使用
  • 网页和网站做哪个好用个人网站备案怎么样才能简单的过
  • 众筹网站哪家好电子商务网站建设规划设计任务书
  • 德德模板网站建设步骤易语言做网站客户端
  • 17做网站郑州ui设计app界面模板
  • 建什么网站收益比较号jsp做的网站运行都需要什么
  • 购买的网站如何换背景中山市网站开发
  • 旺道seo怎么优化网站潍坊手机网站制作
  • 阳光创信-网站建设首选品牌九九建筑网登入