Bhas
Bhas

Reputation: 915

How can I get the current user roles from Spring security 3.1

I have loaded the roles from the database for the current user. And I can access the user role with spring security expression in JSP, and can hide the options and URLs which are not authorized with hasRole. Now I wanted to have it in the servlet and display it in the logs (or store in the user object session). How can we achieve it?

Upvotes: 40

Views: 99788

Answers (6)

Sudhakar Krishnan
Sudhakar Krishnan

Reputation: 860

This may help someone.

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.security.core.userdetails.User;
    
    @GetMapping("/home")
    public String getHomePage(Authentication authentication, Model model) {
        User u = (User) authentication.getPrincipal();
        model.addAttribute("cu", u);
        return "sb/homePage";
    }

And in template Thymeleaf:

Current user:</br>
    <div th:if="${cu}">
        Username: [[${cu.username}]]</br>
        Password: [[${cu.password}]]</br>
        Role: [[${cu.authorities[0]}]]</br>
        Enabled: [[${cu.enabled}]]</br>
        Full: [[${cu}]]</br>
    </div>
    <div th:unless="${cu}">
        Not logged-in!
    </div>

Upvotes: 0

Bogusz
Bogusz

Reputation: 516

If you develop on Java 8, it's getting easier.

To get all user roles:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

Set<String> roles = authentication.getAuthorities().stream()
     .map(r -> r.getAuthority()).collect(Collectors.toSet());

To check if the user has a particular role, for example, ROLE_USER:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

boolean hasUserRole = authentication.getAuthorities().stream()
          .anyMatch(r -> r.getAuthority().equals("ROLE_USER"));

Upvotes: 48

Alireza Fattahi
Alireza Fattahi

Reputation: 45485

To complete both answers...

Here is a Spring security implementation of getUserPrincipal, so you can see that the getUserPrincipal actually is SecurityContextHolder

public Principal getUserPrincipal() {
    Authentication auth = getAuthentication();

    if ((auth == null) || (auth.getPrincipal() == null)) {
        return null;
    }
    return auth;
}

// And the getAuthentication
private Authentication getAuthentication() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (!trustResolver.isAnonymous(auth)) {
        return auth;
    }
    return null;
}

Upvotes: 2

maximdim
maximdim

Reputation: 8169

Try to call getUserPrincipal() from HttpServletRequest.

Upvotes: 7

Dani
Dani

Reputation: 3764

You can try something like this:

Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();

You have the collection of roles in the authorities variable.

Upvotes: 87

Sebastian Ullrich
Sebastian Ullrich

Reputation: 1037

I've created a custom hasRole function for my project.

public static boolean hasRole (String roleName)
{
    return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(roleName));
}

Upvotes: 4

Related Questions