Tutorial 1 : Spring Security Authentication Using Token

spring security logo

Tutorial 1 : Spring Security Authentication Using Token

Authentication using token

In this section we are going to enable authentication token-based in spring MVC by following these steps.
1-The user sends his credentials (username and password) to the server.
2-The server authenticates the credentials and generates a token.
3-The server stores the previously generated token in some storage along with the user identifier and an expiration date.
4-The server sends the generated token to the user.
5-The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication and authorization:
*If the token is valid, the server accepts the request.
*If the token is invalid, the server refuses the request.

Generate the token

A token can be opaque which reveals no details other than the value itself (like a random string) or can be self-contained (like MD5 or SHA algorithme).
src/main/java/com/intellitech /springlabs/util/TokenUtil.java

src/main/java/com/intellitech /springlabs/util/AuthTokenFilter.java

src/main/java/com/intellitech /springlabs/util/SecurityConfig.java

Service for authentication

src/main/java/com/intellitech /springlabs/controller/LoginController.java

src/main/java/com/intellitech /springlabs/util/Constants.java

src/main/java/com/intellitech /springlabs/model/response/UserTransfer.java

By default, the tomcat webserver will reject any request that didn’t originate from localhost.
CORS is a browser feature that protects against cross-site scripting in JavaScript and the web would be a much more dangerous place without it. As always, security comes at a price and in this case that price is that web services that interact with an API on another domain or IP need to allow cross site access in their response headers or just about every modern browser won’t let the response through.
src/main/java/com/intellitech /springlabs/SimpleCORSFilter.java

Avatar for Ayman Ben Amor

Author: Ayman Ben Amor


Post a Comment