V
V
vbNoName2018-10-27 16:24:54
Java
vbNoName, 2018-10-27 16:24:54

How to organize authentication through jwt in Spring?

How to competently and conveniently organize authentication in the Spring REST Api via JWT? I don't want to use session because it's REST and JWT. Token validation must take place on every request that requires authentication. The token is stored either in cookies or passed in headers (this is not so important).
The question is how to make authentication as easy to use as possible in order to write, say, a filter, and forget about it. So that inside each method where authentication is needed, do not pull something like getUser (). I just want to write and forget, but so that this user is already inside the method and you can work with him.
Before writing Api in SparkJava, everything was very simple there. Instead of the standard Route, where it was necessary, it returned a self-written SecuredRoute, which in turn was implemented from the standard Route, and overridden its standard handle method, in which the authorization check logic was written, and if the user is authorized, then handleSecured was passed, in the parameters of which was already a user.
Code for clarity, which was on spark

public interface SecuredRoute extends Route {
    
        @Override
        default Object handle(Request request, Response response) {
            // Логика проверки...
            if (юзер не прошел провеку) {
                response.removeCookie("/", "accessToken");
                return new ErrorResponse(response).errorResponseUnauthenticated();
            }
            return handleSecured(request, response, user);
        }
    
        Object handleSecured(Request request, Response response, User user);
    }

Is it possible to do something similar in Spring?
It seems to me that ideally it would be to create some kind of annotation that would be placed before the method in which authorization is needed, and somehow inject this user into the method

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vbNoName, 2018-10-29
@vbNoName

I came up with the solution myself. Described here https://ru.stackoverflow.com/q/898668/261539

A
alfss, 2018-10-28
@alfss

Or spring security (like https://github.com/szerhusenBC/jwt-spring-security-demo ) and yes, there are filters.
Or try to implement a decorator using annotations.

A
Alexey P, 2018-10-28
@lynxp9

1. See examples https://github.com/search?q=spring+jwt
2. Buy book on Spring Security https://www.amazon.com/s?k=spring+secuity&ref=nb_s...
No documentation I advise. Long and not always clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question