DEV Community

Cover image for Spring Security with JWT

Spring Security with JWT

Jakub Leško on January 14, 2019

Spring Security’s default behavior is easy to use for a standard web application. It uses cookie-based authentication and sessions. Also, it automa...
Collapse
 
petros0 profile image
Petros Stergioulas • Edited

Great Article! Good job!

A quick question: Why here are you checking the header and not the authentication object?

I mean, you already checked the header in getAuthentication()

        var authentication = getAuthentication(request);
        var header = request.getHeader(SecurityConstants.TOKEN_HEADER);

        if (StringUtils.isEmpty(header) || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            filterChain.doFilter(request, response);
            return;
        }
Enter fullscreen mode Exit fullscreen mode

Like this, should also work, or not? :D

        var authentication = getAuthentication(request);

        if (authentication == null) {
            filterChain.doFilter(request, response);
            return;
        }
Enter fullscreen mode Exit fullscreen mode

Again, great article!

Collapse
 
kubadlo profile image
Jakub Leško

Well, you're right. My bad 😀
I'll update the code. Thanks for your attention 🙂

Collapse
 
devc0n profile image
Ricardo Jobse • Edited

For starters, great introduction to JWT security! But i was looking around to see if i could authenticate users with a database instead of the in memory database that is used by default. Do you happen to have an example for this?

EDIT:
Few minutes after i asked the question i stumbled upon the answer...

for those interested i changed this:

auth.inMemoryAuthentication()
        .withUser("user")
        .password(passwordEncoder().encode("password"))
        .authorities("ROLE_USER");

to this

auth.userDetailsService(customUserDetailsService)
        .passwordEncoder(passwordEncoder());

password encoder is just a constructor for a BcryptEncoder, and the userdetail service provides a method to load by username from the repository, and get authorities.

Collapse
 
fmukendi profile image
fmukendi

Hi . Could you please explain where you got the JWT Token From?
When doing the operation below

GET http://localhost:8080/api/private
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJzZWN1cmUtYXBpIiwiYXVkIjoic2VjdXJlLWFwcCIsInN1YiI6InVzZXIiLCJleHAiOjE1NDgyNDI1ODksInJvbCI6WyJST0xFX1VTRVIiXX0.GzUPUWStRofrWI9Ctfv2h-XofGZwcOog9swtuqg1vSkA8kDWLcY3InVgmct7rq4ZU3lxI6CGupNgSazypHoFOA
Collapse
 
kubadlo profile image
Jakub Leško

Hi. You can find JWT in HTTP header Authorization in response from /api/authenticate.

Collapse
 
morensya93 profile image
Faisal Morensya

But from your post it says <Response body is empty>

This response body should be the token right?

Thread Thread
 
kubadlo profile image
Jakub Leško

Yes, response body is empty since JWT is sent via HTTP header.
I'll update that code snipped since it's bit confusing.

Collapse
 
jakemccabenc profile image
JakeMcCabeNC

This is a great explanation! I have been trying to get this to work for weeks and now I get it!

Collapse
 
kubadlo profile image
Jakub Leško

Thank you! I'm writing another article about token refreshing so stay tuned :)

Collapse
 
kzmfullstack4 profile image
Saeid Kazemi

But i'm curious to know how to use UserDetails ?here ?

Collapse
 
kivimango profile image
Kivimango

Hello ! Im waiting for your article about implementing token refreshing.Any plans to do in the future ?

Thread Thread
 
kubadlo profile image
Jakub Leško • Edited

Hello Kivimango. I'm sorry that it takes so long but I have too much work to do so the article is still a draft. But I promise I'll try to complete the article asap.

I already started with code updates in a separate branch, so you can check the progress there

Collapse
 
jakemccabenc profile image
JakeMcCabeNC

Awesome! Another thing that I have been trying to understand is how to extend what you have to a user repository.

Collapse
 
rafasmxp profile image
rafuru

I have like 3 weeks looking for a clear explanation of the basic jwt integration with spring security..

Great Job!

Collapse
 
nottanho profile image
Tân Hồ

Thank for the tutorial. But I don't really agree with your coding style, should be more careful thought. Like the code below, the authentication object should not get from the first place.

    @Override
    protected void doFilterInternal(...) throws ... 
    {
        var authentication = getAuthentication(request);
        var header = request.getHeader(SecurityConstants.TOKEN_HEADER);
        if (StringUtils.isEmpty(header)...
           return...
Collapse
 
mikewakawski profile image
mikewakawski

Thank you for the tutorial. I was wondering how can i implement the @PreAuthorize annotation and the whole roles thing in my spring security(I've looked into other tutorials but it didn't help). Thank you for your time.

Collapse
 
nicoforlano profile image
nicoforlano

Hey! Great article, helped me a lot!

Collapse
 
chriswjarvis profile image
Christopher Jarvis • Edited

Hey just wanted to let you know this was sooooo helpful! Thank you for your time and talent at teaching!

If anyone else is struggling with the seemingly high complexity of the spring security framework, I have a few things to add that I've learned in my struggles:

  1. The reason there is so much is to simplify building enterprise-scale roles-based authentication/authorization logic.
  2. It aims to be an almost out of the box solution for a server rendered mvc style web app If you are just trying to secure the backend for your relatively simple SPA style web app then the framework certainly seems like overkill, but articles like this make it easy to find what you need!
Collapse
 
chriswjarvis profile image
Christopher Jarvis

also if it helps anyone:

if you want to put the username/id whatever you are storing as the subject in jwt onto the request (so that your secured endpoints know which user is accessing):

in AuthorizationFilter#doFilterInternal(): request.setAttribute("username", authentication.getPrincipal());

in ur controllers: public @RequestBody ReturnType yourMethod(@RequestAttribute("username") String username) { ... }

Collapse
 
bvsantos profile image
bvsantos

Hello! First of all really nice guide!
I tried to implement it, i did exactly as you did but i keep getting this error starting on the method authenticationManager.authenticate(authenticationToken) in class JwtAuthenticationFilter:

java.lang.NoSuchMethodError: 'boolean org.springframework.security.crypto.password.PasswordEncoder.upgradeEncoding(java.lang.String)

What could it be?

Collapse
 
lschultebraucks profile image
Lasse Schultebraucks

Very nice!

Collapse
 
kubadlo profile image
Jakub Leško

Thank you :)

Collapse
 
rafalratajczyk profile image
Rafał • Edited

hmmm could you tell me how to this implementation use refresh_token? for example storage this refresh in database. And when token is expired check the refresh_token?
I have similar implementation in my project but I want to extend with refresh_token.

Collapse
 
otojunior profile image
Oto Soares Coelho Junior

In JwtAuthenticationFilter, method attemptAuthentication, the authentication data (username and password) are got from request URL. I need that the username and password got from request body (example JSON: { "username": "john", "password":"mysecret" }). How can I made this?

Collapse
 
kubadlo profile image
Jakub Leško

It's very simple. You just need to update JwtAuthenticationFilter class to parse received JSON data.

Example:

// POJO with your login data
public class LoginData {
    private String username;
    private String password;
    /* getters, setters */
}
// JwtAuthenticationFilter.java
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    var loginData = parseLoginData(request);
    var authenticationToken = new UsernamePasswordAuthenticationToken(loginData.getUsername(), loginData.getPassword());

    return authenticationManager.authenticate(authenticationToken);
}

private LoginData parseLoginData(HttpServletRequest request) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(request.getInputStream(), LoginData.class);
    } catch (IOException exception) {
        // Return empty "invalid" login data
        return new LoginData();
    }
}
Collapse
 
rizz5091660 profile image
Rizky Sani

Great article, clean and straightforward. Awesome!

Collapse
 
eszterbsz profile image
Eszter Szilágyi • Edited

How exactly are the roles checked in this scenario? Suppose you have and endpoint that has in configuration a restriction: hasRole("ADMIN"). How would the authorization filter work then?

Collapse
 
kubadlo profile image
Jakub Leško
  1. JwtAuthenticationFilter saves user data and roles into JWT when the user logs in.
  2. JwtAuthorizationFilter parses the JWT during every HTTP request and load user data and roles from JWT into Spring's security context.
  3. hasRole("ADMIN") reads roles from security context and allows request only if there is "ROLE_ADMIN".

In my example, roles and user are defined in SecurityConfiguration (in-memory user).

Collapse
 
zero2lin profile image
Z

I still see set-cookie in response. And each time request /api/private, it will create a new JSESSIONID


set-cookie: JSESSIONID=...; Path=/; HttpOnly

Collapse
 
kubadlo profile image
Jakub Leško • Edited

It should not create JSESSIONID cookie. Do you have a git repository with your code? We can check it together :)

Collapse
 
birhanetinsae profile image
birhaneTinsae

Great Article! it works fine on Postman everything succeeds but it keeps throwing 403 error on Angular 8 any fixes I can apply?

Collapse
 
mcbbugu profile image
bugu

Very nice! Thank you

Collapse
 
tiagoschaeffer profile image
Tiago Santos

Why do you use "var" ?

Collapse
 
kubadlo profile image
Jakub Leško

It's valid syntax since Java 10. I also think that var is more elegant than full type declaration (it doesn't mean that Java is now dynamically typed).

Collapse
 
fmukendi profile image
fmukendi • Edited

Hi Could you please explain where you get the JWT Token from ? the one that you use for calling the API End Point .

Collapse
 
qhj profile image
千魂剑

Thanks!

Collapse
 
navjot50 profile image
Navjot

But sending the username and password in url localhost:8080/api/authenticate?us... , isn't it a security flaw itself?

Collapse
 
kubadlo profile image
Jakub Leško

For example purposes it's fine. Also, if you're using HTTPS then no one will see query params.

You can send username and password as standard POST data with content-type application/x-www-form-urlencoded and then those params will not be part of the URL.

Collapse
 
sathishk profile image
Sathish Kumar Thiyagarajan

Super Good. Was struggling to understand this for a week :)

Collapse
 
kzmfullstack4 profile image
Saeid Kazemi

tnx

Collapse
 
dineikill profile image
dineikill

Do I need to enable CSRF protection on an api?

Collapse
 
redaalaoui profile image
Réda Housni Alaoui

Hi,

Instead of creating a Servlet Filter, I think you should go the Spring way by creating a org.springframework.security.web.context.SecurityContextRepository implementation.

Collapse
 
mohamadhamid profile image
mohamadhamid

Great post thank to u,
can you integrate social login(google, Facebook ...) with the code.
thanks