简体   繁体   中英

Token Based authentication in Spring

We have a Spring web application which already uses Spring security for authenticating users and granting access to a group of restricted pages. However we have another group of resources that we wish to secure. For this second group we don't want user authentication but instead we want users to go a page: /access.html and enter an access code (previously emailed to them) and then they will be granted access to those resources without login. The access code (token) will only be valid for a limited period of time and then it expires.

Can I use spring security somehow to implement this in parallel to the user authentication setup we already have in place?

Sure, there are a couple of ways to do this. It sounds like all you need to do is create a filter that can check for your token in the session/request and create/update the Spring Security context to have the desired role. Then authorization proceeds as normal.

In particular you will be adding GrantedAuthories to your Authentication object for the Spring Security Context . There are a lot of details to this process and I admit my answer is not complete but a full answer would be pretty extensive.

I have done the similar things with cookie.

You can implement your own filter which extends GenericFilterBean

And then set the config with spring-security like below

<security:http ... >
    ....
    <sec:custom-filter position="FORM_LOGIN_FILTER" ref="cookieAuthenticationFilter" />                                         
</security:http>  

Have a look at the source code of BasicAuthenticationFilter may be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM