当前位置:网站首页>Oauth2.0 - user defined mode authorization - SMS verification code login
Oauth2.0 - user defined mode authorization - SMS verification code login
2022-07-03 06:02:00 【Xiao bichao】
One 、OAuth2.0 - Custom mode authorization
In the last article, we analyzed the current situation , It demonstrates that in the general environment of microservices, we can pass SpringGateWay Realize unified authentication processing , But in the previous demonstration , We are all based on user name and password , But now SMS verification code login has been popularized 、 Wechat login 、QQ Login and other third-party login methods , These methods are obviously not Oauth2.0 Under the four authorization modes provided , Therefore, if we want to realize the login of the third party, we need to customize an authorization mode , Let's take SMS verification code login as an example .
Here is the address of the last article :
Two 、 SMS verification code login
SpringOauth2.0 Although there are only four authorization modes , But it provides very high scalability , We can easily extend the authorization mode , Without a lot of changes , stay SpringOauth2.0 Extended authorization mode , Just inherited AbstractTokenGranter class , And in the construction method super Parent class time , Specify your own authorization ID , When user authentication is passed in grant_type For this ID , Will trigger the generator getOAuth2Authentication Method , Here we can get the parameters passed in by the client , Such as mobile phone number and verification code , Then we compare it with the pre verification code , If OK, You can get the user's information composition according to the mobile phone number UsernamePasswordAuthenticationToken The object is handed over to Oauth2 that will do :
Now write a SmsCodeTokenGranter This is just a demonstration function , Write the user and verification code directly :
public class SmsCodeTokenGranter extends AbstractTokenGranter {
private static final String SMS_GRANT_TYPE = "sms_code";
private UserService userService;
public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices,
ClientDetailsService clientDetailsService,
OAuth2RequestFactory requestFactory,
UserService userService) {
super(tokenServices, clientDetailsService, requestFactory, SMS_GRANT_TYPE);
this.userService = userService;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client,
TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
System.out.println(parameters.toString());
// The mobile number submitted by the client
String phoneNumber = parameters.get("phone");
if (StringUtils.isBlank(phoneNumber)) {
throw new AccessDeniedException("get phone is null !");
}
// The verification code submitted by the client
String smsCode = parameters.get("code");
if (!smsCode.equals("9876")) {
throw new AccessDeniedException("code err!");
}
UserDetails user = userService.loadUserByUsername("admin");
AbstractAuthenticationToken userAuth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
userAuth.setDetails(parameters);
OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(oAuth2Request, userAuth);
}
}
The following needs to be modified AuthorizationServer Configure the generator above into AuthorizationServerEndpointsConfigurer in :
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
@Qualifier("jdbcClientDetailsService")
private ClientDetailsService clientDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired
private JwtAccessTokenConverter accessTokenConverter;
@Autowired
UserService userService;
@Autowired
PasswordEncoder passwordEncoder;
@Bean("jdbcClientDetailsService")
public ClientDetailsService clientDetailsService(DataSource dataSource) {
JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
clientDetailsService.setPasswordEncoder(passwordEncoder);
return clientDetailsService;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Bean
public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
return new JdbcAuthorizationCodeServices(dataSource);// Set how the authorization code of the authorization code mode is accessed
}
@Bean
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service = new DefaultTokenServices();
service.setClientDetailsService(clientDetailsService);
service.setSupportRefreshToken(true);
service.setTokenStore(tokenStore);
// Token enhancement
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
// Content enhancement
tokenEnhancers.add(tokenEnhancer());
tokenEnhancers.add(accessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
service.setTokenEnhancer(tokenEnhancerChain);
service.setAccessTokenValiditySeconds(7200); // Token default validity 2 Hours
service.setRefreshTokenValiditySeconds(259200); // Refresh token default validity 3 God
return service;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.authenticationManager(authenticationManager)// Authentication manager
.authorizationCodeServices(authorizationCodeServices)// Authorization code service
.tokenGranter(tokenGranter(endpoints))
.tokenServices(tokenService())// Token management service
.allowedTokenEndpointRequestMethods(HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()") //oauth/token_key It's public
.checkTokenAccess("permitAll()") //oauth/check_token Open
.allowFormAuthenticationForClients(); // Forms authentication ( Claim Token )
}
/**
* JWT Content enhancement
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return (accessToken, authentication) -> {
Map<String, Object> additionalInfo = new HashMap<>();
additionalInfo.put("userid", -1);
Authentication auth = authentication.getUserAuthentication();
if (auth != null) {
UserEntity user = (UserEntity) auth.getPrincipal();
additionalInfo.put("userid", user.getId());
}else {
String clientId = authentication.getOAuth2Request().getClientId();
String grantType = authentication.getOAuth2Request().getRequestParameters().get("grant_type");
if (Objects.equals(clientId, "c1") && Objects.equals(grantType, "client_credentials")) {
additionalInfo.put("userid", "root");
}
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
};
}
/**
* Add a custom authorization type
*
* @return List<TokenGranter>
*/
private TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints) {
// endpoints.getTokenGranter() obtain SpringSecurity OAuth2.0 Existing authorization types
List<TokenGranter> granters = new ArrayList<TokenGranter>(Collections.singletonList(endpoints.getTokenGranter()));
// Build SMS authentication authorization type
SmsCodeTokenGranter smsCodeTokenGranter = new SmsCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
endpoints.getOAuth2RequestFactory(),userService);
// Add SMS authorization type to the collection
granters.add(smsCodeTokenGranter);
// Returns all types
return new CompositeTokenGranter(granters);
}
}
3、 ... and 、 test
Use PostMan send out POST request :
http://localhost:8020/oauth/token?client_id=c1&client_secret=secret&grant_type=sms_code&phone=110&code=9562
Be careful :grant_type To transmit sms_code
You can see that what's coming back is Unauthorized grant type: sms_code Unauthorized type , This is because c1 This client does not sms_code Authentication type , to c1 add sms_code type :

Now retest :
I have already written the return , Enter the correct verification code below :
http://localhost:8020/oauth/token?client_id=c1&client_secret=secret&grant_type=sms_code&phone=110&code=9876

The token has been successfully obtained .

Love little buddy can pay attention to my personal WeChat official account. , Get more learning materials !
边栏推荐
- BeanDefinitionRegistryPostProcessor
- Jedis source code analysis (II): jediscluster module source code analysis
- [teacher Zhao Yuqiang] kubernetes' probe
- How does win7 solve the problem that telnet is not an internal or external command
- Final review Day8
- Simple solution of small up main lottery in station B
- Kubernetes notes (VIII) kubernetes security
- Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
- 88. Merge two ordered arrays
- Redhat7 system root user password cracking
猜你喜欢

Analysis of the example of network subnet division in secondary vocational school

Es remote cluster configuration and cross cluster search

理解 期望(均值/估计值)和方差

Bio, NiO, AIO details

JDBC connection database steps

Simple handwritten ORM framework

智牛股项目--04

Personal outlook | looking forward to the future from Xiaobai's self analysis and future planning

Kubernetes notes (VIII) kubernetes security

项目总结--2(Jsoup的基本使用)
随机推荐
2022.6.30DAY591
Apt update and apt upgrade commands - what is the difference?
深度学习,从一维特性输入到多维特征输入引发的思考
Apple submitted the new MAC model to the regulatory database before the spring conference
[minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]
Kubernetes notes (IX) kubernetes application encapsulation and expansion
MySQL startup error: several solutions to the server quit without updating PID file
Kubernetes notes (I) kubernetes cluster architecture
Kubernetes notes (IV) kubernetes network
Beandefinitionregistrypostprocessor
从小数据量分库分表 MySQL 合并迁移数据到 TiDB
Kubernetes cluster environment construction & Deployment dashboard
Kubernetes notes (VI) kubernetes storage
[explain in depth the creation and destruction of function stack frames] | detailed analysis + graphic analysis
Intel's new GPU patent shows that its graphics card products will use MCM Packaging Technology
Detailed explanation of iptables (1): iptables concept
How to create your own repository for software packages on Debian
Kubernetes resource object introduction and common commands (V) - (configmap)
Ansible firewall firewalld setting
Jetson AgX Orin platform porting ar0233 gw5200 max9295 camera driver