Spring security returns wrong loggedin user AFTER override UserDetailsContextMapper - spring

I am using spring security with LDAP in a spring boot application.
Everything was working fine before I did below changes in security config as below.
Override UserDetailsContextMapper to set ROLE for the users.
Restrict URLs based on user role.
Below are the code changes to achieve above 2 things.
1. UserDetailsContextMapper:
#Component
public class UserDetailsContextMapperImpl implements UserDetailsContextMapper, Serializable{
private static final long serialVersionUID = 3962976258168853954L;
private static Logger logger = LoggerFactory.getLogger(UserDetailsContextMapperImpl.class);
#SuppressWarnings("rawtypes")
#Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authority) {
List<GrantedAuthority> mappedAuthorities = new ArrayList<GrantedAuthority>();
try{
Attributes attrListOuter = ctx.getAttributes();
Attribute attrListInner = attrListOuter.get(UserConstant.MEMBER_OF);
logger.info("memberOf: " + attrListInner.getID());
for (NamingEnumeration enumInner = attrListInner.getAll(); enumInner.hasMore();){
String CN = (String)enumInner.next();
logger.info("CN value: " + CN);
if(CN.contains(UserConstant.MASTER_GROUP_PROJ_NAME)){
logger.info("Logged in user is authorized to acccess Rates Toronto application: {}", username );
mappedAuthorities.add(new SimpleGrantedAuthority(UserConstant.ROLE_ABC));// adding ROLE_ABC to APP/LDAP users.
logger.info("User {} Role set as : {}", username, UserConstant.ROLE_ABC );
break;
}else if(CN.contains(UserConstant.GROUP_XYZ)){
mappedAuthorities.add(new SimpleGrantedAuthority(UserConstant.ROLE_XYZ));
logger.info("User {} Role set as : {}", username, UserConstant.ROLE_XYZ );
break;
}
}
if(mappedAuthorities.isEmpty()){
logger.info("Logged in user is NOT authorized to access ABCD application : {}", username );
}
}catch(Exception ex){
logger.info("Exception while mapping UserDetails with LDAP" + ex.getMessage());
}
//Returning Spring Seurity's User object.
return new org.springframework.security.core.userdetails.User(username, "", true, true, true, true, mappedAuthorities);
}
2. Restrict URLs based on user role:
In my websecurity configuration class,
#Configuration
#EnableWebSecurity
public class AbcWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
.......
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/**").hasAnyRole("REST","ABC").and().httpBasic().and().formLogin();
http.authorizeRequests().antMatchers("/xyz/**").hasRole("XYZ").and().httpBasic();
http.authorizeRequests().antMatchers("/abc/**").hasRole("ABC").and().httpBasic(); // Users who are accessing the URLS/application via application's UI. ie. Business User.
http.headers().contentTypeOptions().xssProtection().cacheControl().httpStrictTransportSecurity().frameOptions().disable();
http.headers().addHeaderWriter(new StaticHeadersWriter("Cache-Control","no-cache, no-store, max-age=0, must-revalidate"));
http.headers().addHeaderWriter(new StaticHeadersWriter("Expires","0"));
http.csrf().disable();
http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
super.configure(http);
}
and ......
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().userDetailsContextMapper(userDetailsContextMapperImpl).userSearchFilter(SAM_ACC).userSearchBase(base).contextSource().url(url).managerDn(managerDn).managerPassword(password);
auth.inMemoryAuthentication().withUser(restUserName).password(restPassword).roles(restRole);
//This publisher will trigger AuthenticationFailureBadCredentialsEvent (AbstractAuthenticationFailureEvent)
auth.authenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher));
}
After the above changes, getting loggedIn user giving wrong user ( sometimes),
This is not happening every-time, but happening intermittently.
I am using below code to get the current logged in user.
Authentication authentication = securityContextHolder.getContext().getAuthentication();
if (authentication == null)
return null;
org.springframework.security.core.userdetails.User userDetails = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
String userName = userDetails.getUsername();
I am unable to find where I am missing, any pointers/direction will be very helpful.
It is returning wrong user from already authenticated users.
I am using spring boot 1.2.0 which uses spring security 3.2.5 by default

Related

How to set a custom principal object during or after JWT authentication?

I've changed the way a user is authenticated in my backend. From now on I am receiving JWT tokens from Firebase which are then validated on my Spring Boot server.
This is working fine so far but there's one change which I am not too happy about and it's that the principal-object is now a org.springframework.security.oauth2.jwt.Jwt and not a AppUserEntity, the user-model, like before.
// Note: "authentication" is a JwtAuthenticationToken
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Jwt jwt = (Jwt) authentication.getPrincipal();
So, after some reading and debugging I found that the BearerTokenAuthenticationFilter essentially sets the Authentication object like so:
// BearerTokenAuthenticationFilter.java
AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request);
// Note: authenticationResult is our JwtAuthenticationToken
Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authenticationResult);
SecurityContextHolder.setContext(context);
and as we can see, this on the other hand comes from the authenticationManager which is a org.springframework.security.authentication.ProviderManager and so on. The rabbit hole goes deep.
I didn't find anything that would allow me to somehow replace the Authentication.
So what's the plan?
Since Firebase is now taking care of user authentication, a user can be created without my backend knowing about it yet. I don't know if this is the best way to do it but I intend to simply create a user record in my database once I discover a valid JWT-token of a user which does not exist yet.
Further, a lot of my business logic currently relies on the principal being a user-entity business object. I could change this code but it's tedious work and who doesn't want to look back on a few lines of legacy code?
I did it a bit different than Julian Echkard.
In my WebSecurityConfigurerAdapter I am setting a Customizer like so:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2ResourceServer()
.jwt(new JwtResourceServerCustomizer(this.customAuthenticationProvider));
}
The customAuthenticationProvider is a JwtResourceServerCustomizer which I implemented like this:
public class JwtResourceServerCustomizer implements Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>.JwtConfigurer> {
private final JwtAuthenticationProvider customAuthenticationProvider;
public JwtResourceServerCustomizer(JwtAuthenticationProvider customAuthenticationProvider) {
this.customAuthenticationProvider = customAuthenticationProvider;
}
#Override
public void customize(OAuth2ResourceServerConfigurer<HttpSecurity>.JwtConfigurer jwtConfigurer) {
String key = UUID.randomUUID().toString();
AnonymousAuthenticationProvider anonymousAuthenticationProvider = new AnonymousAuthenticationProvider(key);
ProviderManager providerManager = new ProviderManager(this.customAuthenticationProvider, anonymousAuthenticationProvider);
jwtConfigurer.authenticationManager(providerManager);
}
}
I'm configuring the NimbusJwtDecoder like so:
#Component
public class JwtConfig {
#Bean
public JwtDecoder jwtDecoder() {
String jwkUri = "https://www.googleapis.com/service_accounts/v1/jwk/securetoken#system.gserviceaccount.com";
return NimbusJwtDecoder.withJwkSetUri(jwkUri)
.build();
}
}
And finally, we need a custom AuthenticationProvider which will return the Authentication object we desire:
#Component
public class JwtAuthenticationProvider implements AuthenticationProvider {
private final JwtDecoder jwtDecoder;
#Autowired
public JwtAuthenticationProvider(JwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) authentication;
Jwt jwt;
try {
jwt = this.jwtDecoder.decode(token.getToken());
} catch (JwtValidationException ex) {
return null;
}
List<GrantedAuthority> authorities = new ArrayList<>();
if (jwt.hasClaim("roles")) {
List<String> rolesClaim = jwt.getClaim("roles");
List<RoleEntity.RoleType> collect = rolesClaim
.stream()
.map(RoleEntity.RoleType::valueOf)
.collect(Collectors.toList());
for (RoleEntity.RoleType role : collect) {
authorities.add(new SimpleGrantedAuthority(role.toString()));
}
}
return new JwtAuthenticationToken(jwt, authorities);
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(BearerTokenAuthenticationToken.class);
}
}
This is working fine so far but there's one change which I am not too happy about and it's that the principal-object is now a org.springframework.security.oauth2.jwt.Jwt and not a AppUserEntity, the user-model, like before.
In my application I have circumvented this by rolling my own JwtAuthenticationFilter instead of using BearerTokenAuthenticationFilter, which then sets my User Entity as the principal in the Authentication object. However, in my case this constructs a User barely from the JWT claims, which might be bad practice: SonarLint prompts to use a DTO instead to mitigate the risk of somebody injecting arbitrary data into his user record using a compromised JWT token. I don't know if that is a big deal - if you can't trust your JWTs, you have other problems, IMHO.
I don't know if this is the best way to do it but I intend to simply create a user record in my database once I discover a valid JWT-token of a user which does not exist yet.
Keep in mind that JWTs should be verified by your application in a stateless manner, solely by verifying their signature. You shouldn't hit the database every time you verify them. Therefor it would be better if you create a user record using a method call like
void foo(#AuthenticationPrincipal final Jwt jwt) {
// only invoke next line if reading JWT claims is not enough
final User user = userService.findOrCreateByJwt(jwt);
// TODO method logic
}
once you need to persist changes to the database that involve this user.
Since
SecurityContextHolder.setContext(context);
won't work for
request.getUserPrincipal();
you may create a custom class extending HttpServletRequestWrapper
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class UserPrincipalHttpServletRequest extends HttpServletRequestWrapper {
private final Principal principal;
public UserPrincipalHttpServletRequest(HttpServletRequest request, Principal principal) {
super(request);
this.principal = principal;
}
#Override
public Principal getUserPrincipal() {
return principal;
}
}
then in your filter do something like this:
protected void doFilterInternal(HttpServletRequest request){
. . .
// create user details, roles are required
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("SOME ROLE"));
UserDetails userDetails = new User("SOME USERNAME", "SOME PASSWORD", authorities);
// Create an authentication token
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// follow the filter chain, using the new wrapped UserPrincipalHtppServletRequest
chain.doFilter(new UserPrincipalHttpServletRequest(request, usernamePasswordAuthenticationToken), response);
// all filters coming up, will be able to run request.getUserPrincipal()
}
According Josh Cummings answer in issue #7834 make configuration:
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
http...
.oauth2ResourceServer(oauth2 -> oauth2.jwt(
jwt -> jwt.jwtAuthenticationConverter(JwtUtil::createJwtUser)))
...
return http.build();
}
and implement factory method, e.g:
public class JwtUtil {
public static JwtUser createJwtUser(Jwt jwt) {
int id = ((Long) jwt.getClaims().get("id")).intValue();
String rawRoles = (String) jwt.getClaims().get("roles");
Set<Role> roles = Arrays.stream(rawRoles.split(" "))
.map(Role::valueOf)
.collect(Collectors.toSet());
return new JwtUser(jwt, roles, id);
}
}
public class JwtUser extends JwtAuthenticationToken {
public JwtUser(Jwt jwt, Collection<? extends GrantedAuthority> authorities, int id) {
super(jwt, authorities);
....
}
}
Take in note, that controller's methods should inject JwtUser jwtUser without any #AuthenticationPrincipal

Using JWT with #PathVariable but only allow access url for spesific user

I am creating simple Rest social media application with Spring Boot. I use JWT for authentication in application.
In my mobile application when users register, i am getting some information from users and create account and profile of the user.
By the way, you can see (simplified) database object of account and profile. I use Mongo DB for database.
account:
{
“_id”: “b6164102-926e-47d8-b9ff-409c44dc47c0“,
“email”: “xxx#yy.com”
….
}
profile:
{
“_id”: “35b06171-c16a-4559-90f3-df81ace6d64a“,
“accountId”: “b6164102-926e-47d8-b9ff-409c44dc47c0”,
profileImages: [
{
“imageId”: “1431b0bc-feb7-436d-9d3a-7b9094547bf6”,
“imageLink”: “https://this_is_some_link_to_image.com
}
….
]
….
}
When user login to app, i add accountId to JWT and then in my mobile app i call below endpoint to get profile information of user. I take accountId from jwt and find profile of that account id.
#GetMapping("/profiles")
public ResponseEntity<BaseResponse> getUserProfile(#AuthenticationPrincipal AccountId accountId) {
var query = new Query(accountId);

 var presenter = new GetUserProfilePresenter();


 useCase.execute(query, presenter);


 return presenter.getViewModel();
}
In the app, users can upload photo to their profile using below endpoint;
#PostMapping(path = "/profiles/{profileId}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<BaseResponse> uploadProfileImage(
#PathVariable("profileId") UUID profileId, #RequestParam("image") MultipartFile image) throws IOException {

......
}
Everything works fine but the problem is someone can use their token to call this url with another person’s profileId. Because profileId is not a hidden id. In my mobile app users can shuffle and see other users profile using below url.
This url is accessible by any authenticated users.
#GetMapping(path = "/profiles/{profileId}")
public ResponseEntity<BaseResponse> getProfile(#PathVariable("profileId") UUID profileId) {
......
}
Now, my question is how can i make "/profiles/{profileId}/images" this url is only accesible for user of this profile without changing path format.
For exampe;
User A - Profile Id = XXX
User B - Profile Id = YYY
I want that if User A calls this url with own JWT Token, uploads image only to own profile not another one profile.
I have come up with some solutions but these solutions cause me to change the url path;
Solution 1:
I can use accountId in the jwt. Find profile of user with this accountId so that, every call to this url guaranteed upload image only to profile of token user.
But this solution change url path like below because i dont need to get any profileId from path.
#PostMapping(path = "/profiles/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

public ResponseEntity<BaseResponse> uploadProfileImage(

 #AuthenticationPrincipal AccountId accountId, #RequestParam("image") MultipartFile image) throws IOException {


 ......
}
Solution 2:
This is very similar to first solution only different is when i create jwt for user. I will put profileId of user to inside of JWT. So when the user calls the url i will get profileId from jwt and put inside of Authentication object. And in the controller i will get this profileId for using to find profile of user then upload image to this spesific profile.
But also, this solution change url path format because i dont need to get profileId from url path.
So if i back to my main question. What is the best practices and solutions for these kinda problems and situations?
~~~EDIT~~~
For those whose wonder, i didn't change my path. Actually i implemented solution 1 with a twist.
Now i use accountId from JWT and profileId at the same time so when i want to find a profile of exactly that user i search the database using accountId and profileId together.
With this change, i didn't need to change other paths.
For example; (GET) /profiles/{profileId} this path still meaningful for all authenticated users.
But (POST) /profiles/{profileId}/images this path only meaningful for that spesific (owner of token) user.
By the way, i starts paths with "api/admin/**" prefix for my admin role operations.
Final code (Controller);
#PostMapping(path = "/profiles/{profileId}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<BaseResponse> uploadProfileImage(
#AuthenticationPrincipal AccountId accountId,
#PathVariable("profileId") UUID profileId,
#RequestParam("image") MultipartFile image) throws IOException {
....
}
Final code (Repository);
#Repository
public interface ProfileJpaRepository extends MongoRepository<ProfileDto, String> {
Optional<ProfileDto> findByAccountId(String accountId);
Optional<ProfileDto> findByIdAndAccountId(String profileId, String accountId);
}
The best practice to handle this kind of scenarios is to have two endpoints, each needing different kind of permissions:
"/profiles/{profileId}/images" will be available for admins, so that if an admin wants to change another user's profile image, they can do so by calling this endpoint.
"/profiles/images" will be responsible for changing the most generic users with the lowest privileges.
So, in both scenarios you need to extract the AccountId from the JWT and you should not get the AccountId from the user directly, unless for administration purposes where you check the privileges to authorize the user.
Now, the best way to implement such a system, is to use Spring Security and to create a custom AuthenticationToken, then to customize AbstractUserDetailsAuthenticationProvider, * AbstractAuthenticationProcessingFilter* and UsernamePasswordAuthenticationToken.
After doing so, you can then configure Spring to use the custom provider for authentication.
UsernamePasswordAuthenticationToken
public class JwtAuthenticationToken extends UsernamePasswordAuthenticationToken {
private Payload payload; // Payload can be any model class that encapsulates the payload of the JWT.
private boolean creationAllowed;
public JwtAuthenticationToken(String jwtToken) throws Exception {
super(null, jwtToken);
// Verify JWT and get the payload
this.payload = // set the payload
}
public JwtAuthenticationToken(String principal, JwtAuthenticationToken authToken, Collection<? extends GrantedAuthority> authorities) {
super(principal, authToken.getCredentials(), authorities);
this.payload = authToken.payload;
authToken.eraseCredentials(); // not sure if this is needed
}
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
} else {
super.setAuthenticated(false);
}
}
public Payload getPayload() {
return this.firebaseToken;
}
public boolean isCreationAllowed() {
return creationAllowed;
}
public void setCreationAllowed(boolean creationAllowed) {
this.creationAllowed = creationAllowed;
}
}
AbstractUserDetailsAuthenticationProvider
#Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
#Autowired
AppUserService appUserService;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(JwtAuthenticationToken.class, authentication, () ->
this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only JwtAuthenticationToken is supported")
);
JwtAuthenticationToken jwtAuthToken = (JwtAuthenticationToken) authentication;
String principal;
try {
principal = jwtAuthToken.getPayload().getEmail(); // Here I'm using email as the user identifier, this can be anything, for example AccountId
} catch (RuntimeException re) {
throw new AuthenticationException("Could not extract user's email address.");
}
AppUser user = (AppUser) this.retrieveUser(principal, jwtAuthToken);
return this.createSuccessAuthentication(principal, jwtAuthToken, user);
}
#Override
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
JwtAuthenticationToken result = new JwtAuthenticationToken((String) principal, (JwtAuthenticationToken) authentication, user.getAuthorities());
result.setDetails(user);
return result;
}
#Override
public UserDetails retrieveUser(String s, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
UserDetails userDetails = appUserService.loadUserByUsername(s);
JwtAuthenticationToken jwtAuthToken = (JwtAuthenticationToken) usernamePasswordAuthenticationToken;
if (userDetails != null)
return userDetails; // You need to create an UserDetails which will be set by the framework to the Security Context as the authenticated user, this will be useful later when you want to check the privileges.
else
throw new AuthenticationException("Creating the user details is not allowed.");
}
#Override
protected void additionalAuthenticationChecks(final UserDetails d, final UsernamePasswordAuthenticationToken auth) {
// Nothing to do
}
#Override
public boolean supports(Class<?> authentication) {
return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
}
}
AbstractAuthenticationProcessingFilter
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter() {
super("/**"); // The path that this filter needs to process, use "/**" to make sure all paths must be proessed.
}
#Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true; // Here I am returning true to require authentication for all requests.
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String authorization = request.getHeader("Authorization");
if (authorization == null || !authorization.startsWith("Bearer "))
throw new AuthenticationException("No JWT token found in request headers");
String authToken = authorization.substring(7);
JwtAuthenticationToken token = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(token);
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
// Authentication process succeed, filtering the request in.
// As this authentication is in HTTP header, after success we need to continue the request normally
// and return the response as if the resource was not secured at all
chain.doFilter(request, response);
}
#Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
super.unsuccessfulAuthentication(request, response, failed);
// Authentication process failed, filtering the request out.
}
}
UserDetails
public class AppUser implements UserDetails {
// A class to be used as a container for user details, you can add more details specific to your application here.
}
Finally, you need to configure Spring boot to use this classes:
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
// -- public paths, for example: swagger ui paths
new AntPathRequestMatcher("/swagger-ui.html"),
new AntPathRequestMatcher("/swagger-resources/**"),
new AntPathRequestMatcher("/v2/api-docs"),
new AntPathRequestMatcher("/webjars/**")
);
private JwtAuthenticationProvider provider;
public SecurityConfig(JwtAuthenticationProvider provider) {
this.provider = provider;
}
#Override
public void configure(final WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS) // Allowing browser pre-flight
.requestMatchers(PUBLIC_URLS);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet authenticated
//.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.authenticationEntryPoint(forbiddenEntryPoint())
.and()
.authenticationProvider(this.provider)
.addFilterBefore(jwtAuthenticationFilter(), AnonymousAuthenticationFilter.class)
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
}
#Bean
JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
final JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
filter.setAuthenticationManager(this.authenticationManager());
filter.setAuthenticationSuccessHandler(this.successHandler());
filter.setAuthenticationFailureHandler(this.failureHandler());
return filter;
}
#Bean
JwtAuthenticationSuccessHandler successHandler() {
return new JwtAuthenticationSuccessHandler();
}
#Bean
JwtAuthenticationFailureHandler failureHandler() {
return new JwtAuthenticationFailureHandler();
}
/**
* Disable Spring boot automatic filter registration.
*/
#Bean
FilterRegistrationBean disableAutoRegistration(JwtAuthenticationFilter filter) {
final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
#Bean
AuthenticationEntryPoint forbiddenEntryPoint() {
return new HttpStatusEntryPoint(FORBIDDEN);
}
}
AuthenticationFailureHandler
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
private ObjectMapper objectMapper = new ObjectMapper();
#Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
Map<String, Object> data = new HashMap<>();
data.put("exception", e.getMessage());
httpServletResponse.getOutputStream().println(objectMapper.writeValueAsString(data));
}
}
AuthenticationSuccessHandler
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
}
}
OKAY!
Now that you have implemented the security correctly, you can access user details and privileges from anywhere using the last piece:
UserDetailsService
#Service
public class AppUserService implements UserDetailsService {
#Autowired
private AppUserRepository appUserRepository;
public AppUser getCurrentAppUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null)
return (AppUser) authentication.getDetails();
return null;
}
public String getCurrentPrincipal() {
return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
#Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<AppUser> appUserOptional = this.appUserRepository.findByEmailsContains(new EmailEntity(s)); // This should be changed in your case if you are using something like AccountId
appUserOptional.ifPresent(AppUser::loadAuthorities);
return appUserOptional.orElse(null);
}
}
Great.
Let's see how to use it in your Controllers:
#PostMapping(path = "/profiles/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<BaseResponse> uploadProfileImage(#RequestParam("image") MultipartFile image) throws IOException {

AppUser user = this.appUserService.getCurrentAppUser();
Long id = user.getAccountId(); // Or profile id or any other identifier that you needed and extracted from the JWT after verification.
// set the profile picture.
// save changes of repository and return.
}
For admin purposes:
#PreAuthorize ("hasRole('ROLE_ADMIN')")
#PostMapping(path = "/profiles/{profileId}/images", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<BaseResponse> uploadProfileImage(
#PathVariable("profileId") UUID profileId, #RequestParam("image") MultipartFile image) throws IOException {

AppUser user = this.appUserService.getCurrentAppUser();
// set the profile picture using profileId parameter
// save changes of repository and return.
}
The only remaining task is to assign the ROLE_ADMIN to the right user when loading it from the database. To do this, there are a lot of different approaches and it totally depends on your requirements. Overall, you can save a role in the database and relate it to a specific user and simply load it using an Entity.
Let's get few things right here , I am assuming that you have like two entities - Account and Profile and you wish to upload/update new profile image using same API -
#PostMapping(path = "/profiles/{profileId}/images
If ADMIN role , update profile image for #PathVariable("profileId") OR if USER role update their own profile image using #PathVariable("profileId") and not any other Profile entity image using ProfileId if current user is authenticated.
Please check this link for Role-Permission Authentication
Spring Boot : Custom Role - Permission Authorization using SpEL
User Principal
#Getter
#Setter
#Builder
public class UserPrincipal implements UserDetails {
/**
* Generated Serial ID
*/
private static final long serialVersionUID = -8983688752985468522L;
private Long id;
private String email;
private String password;
private Collection<? extends GrantedAuthority> authorities;
private Collection<? extends GrantedAuthority> permissions;
public static UserPrincipal createUserPrincipal(Account account) {
if (userDTO != null) {
List<GrantedAuthority> authorities = userDTO.getRoles().stream().filter(Objects::nonNull)
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
List<GrantedAuthority> permissions = account.getRoles().stream().filter(Objects::nonNull)
.map(Role::getPermissions).flatMap(Collection::stream)
.map(permission -> new SimpleGrantedAuthority(permissionDTO.getName().name()))
.collect(Collectors.toList());
return UserPrincipal.builder()
.id(account.getId())
.email(account.getEmail())
.authorities(authorities)
.permissions(permissions)
.build();
}
return null;
}
AuthenticationFilter
public class AuthTokenFilter extends OncePerRequestFilter {
#Autowired
private JwtUtils jwtUtils;
#Autowired
private CustomUserDetailsService customUserDetailsService;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwtToken = getJwtTokenFromHttpRequest(request);
if (StringUtils.isNotBlank(jwtToken) && jwtUtils.validateToken(jwtToken)) {
Long accountId = jwtUtils.getAccountIdFromJwtToken(jwtToken);
UserDetails userDetails = customUserDetailsService.loadUserByUserId(accountId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails
.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception exception) {
}
filterChain.doFilter(request, response);
}
private String getJwtTokenFromHttpRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (!StringUtils.isEmpty(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}
AuthUtil
#UtilityClass
public class AuthUtils {
public boolean isAdmin(UserPrincipal userPrincipal){
if(CollectionUtils.isNotEmpty(userPrincipal.getAuthorities())){
return userPrincipal.getRoles().stream()
.filter(Objects::nonNull)
.map(GrantedAuthority::getName)
.anyMatch(role -> role.equals("ROLE_ADMIN"));
}
return false;
}
}
Profile Service
#Service
public class ProfileService {
#Autowired
private ProfileRepository profileRepository;
public Boolean validateProfileIdForAccountId(Integer profileId, Long accountId) throws NotOwnerException,NotFoundException {
Profile profile = profileRepository.findByAccountId(profileId,accountId);
if(profile == null){
throw new NotFoundException("Profile does not exists for this account");
} else if(profile.getId() != profileId){
throw new NotOwnerException();
}
return true;
}
}
ProfileController
#PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
#PostMapping(path = "/profiles/{profileId}/images", consumes =
MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<BaseResponse> uploadProfileImage(
#AuthenticationPrincipal UserPrincipal currentUser,
#PathVariable("profileId") UUID profileId,
#RequestParam("image") MultipartFile image) throws IOException {
if(!AuthUtils.isAdmin(currentUser)){
profileService.validateProfileIdForAccountId(profileId, currentUser.getId());
}
}
Now you can validate whether the #PathVariable("profileId") does indeed belong to the authenticated CurrentUser, you are also checking if the CurrentUser is ADMIN.
You can also add & check any specific permission for ROLES for facilitating UPLOAD/UPDATE
#PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER') or hasPermission('UPDATE')")

How check user role and get authenticated username in Spring Security JWT authentication

I'm working on Spring Security implementation with JWT authentication. I'm not sure how to check the user role and get authenticated user at method level. I saw this example on Internet:
#PostMapping("{id}")
#Secured({"ROLE_ADMIN"})
public ResponseEntity<?> save(Authentication authentication, Principal principal, #PathVariable Integer id, #RequestBody UserNewDTO dto) {
........
}
Do I need to extract the user type from the JWT token is there is other way to implement this? Using only #Secured({"ROLE_ADMIN"}) looks to me uncomplete.
Looks like this code is used to get user if session type is used, I get NPE. Do you know for JWT how I can the the user?
Github Full source: https://github.com/rcbandit111/OAuth2/blob/master/src/main/java/org/engine/rest/DataPagesController.java
There are many ways to design authority-based access to the APIs using annotations as well as security configurations based on the endpoints.
Annotations:
#Secured
#PreAuthorize
#PostAuthorize
#RolesAllowed
#PreFilter
#PostFilter
In order to use the annotations you need to enable the security configurations as follow
#Configuration
#EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
The prePostEnabled property enables Spring Security pre/post annotations
The securedEnabled property determines if the #Secured annotation should be enabled
The jsr250Enabled property allows us to use the #RoleAllowed annotation
#Secured & #RoleAllowed
Users who have the given role are able to execute the method. The #RoleAllowed annotation is the JSR-250’s equivalent annotation of the #Secured annotation.
#Secured({ "ROLE_ADMIN", "ROLE_SUPERADMIN" })
public ResponseEntity<?> save(...) {
...
}
#RolesAllowed({ "ROLE_ADMIN", "ROLE_SUPERADMIN" })
public ResponseEntity<?> save(...) {
...
}
#PreAuthorize & #PostAuthorize
The #PreAuthorize annotation checks the given expression before entering the method, whereas, the #PostAuthorize annotation verifies it after the execution of the method and could alter the result.
#PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPERADMIN')")
public ResponseEntity<?> save(...) {
...
}
The major difference between #PreAuthorize & #PostAuthorize and #Secured is that #Secured does not support the SpEL (Spring Expression Language). To check more difference you may read more details here
#PreAuthorize("#username == authentication.principal.username")
public String methodX(String username) {
//...
}
#PostAuthorize("#username == authentication.principal.username")
public String methodY(String username) {
//...
}
Here, a user can invoke the methodX only if the value of the argument username is the same as the current principal's username. You can check the other possible SpEL (Spring Expression Language) customization here
You can get the more details from the here
Using configure(HttpSecurity http) and configure(WebSecurity web) method.
#EnableWebSecurity
#EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/**")
.antMatchers("/test/**");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.antMatchers("/api/**").hasAuthority(AuthoritiesConstants.USER)
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
// #formatter:on
}
}
configure(WebSecurity web)
Endpoint used in this method ignores the spring security filters, security features (secure headers, csrf protection etc) are also ignored and no security context will be set and can not protect endpoints for Cross-Site Scripting, XSS attacks, content-sniffing.
configure(HttpSecurity http)
Endpoint used in this method ignores the authentication for endpoints used in antMatchers and other security features will be in effect such as secure headers, CSRF protection, etc.
You can use the hasRole(), hasAnyRole(), hasAuthority(), hasAnyAuthority() methods with the configure(HttpSecurity http). Note that with the hasRole(), hasAnyRole() method you don't need to use the ROLE_ prefix while with other two you have to use the ROLE_
To get the difference and usage you may get the details here
You can also create the utils method as follows which might be helpful.
/**
* Get the login of the current user.
*
* #return the login of the current user.
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
});
}
/**
* Check if a user is authenticated.
*
* #return true if the user is authenticated, false otherwise.
*/
public static boolean isAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.addAll(authentication.getAuthorities());
return authorities.stream()
.noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS));
})
.orElse(false);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the {#code isUserInRole()} method in the Servlet API.
*
* #param authority the authority to check.
* #return true if the current user has the authority, false otherwise.
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.addAll(authentication.getAuthorities());
return authorities.stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority));
})
.orElse(false);
}
public static Optional<Authentication> getAuthenticatedCurrentUser() {
log.debug("Request to get authentication for current user");
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication());
}
UPDATE
#Component("userVerifier")
public class UserVerifier {
public boolean isPermitted(Authentication authentication) {
String PERMITTED_USERNAME = Arrays.asList("abc", "xyz");
return PERMITTED_USERNAME.stream.anyMatch(username -> authentication.getName().equals(username));
}
}
In security configurations we can use configure(HttpSecurity http) as follow which will invoke the isPermitted() method.
http
.authorizeRequests()
.antMatchers("/your-endpoint/{id}")
.access("#userVerifier.isPermitted(authentication)")
...
OR using the annotation as follows:
#PreAuthorize("#userVerifier.isPermitted(authentication)")
#PostMapping("{id}")
public ResponseEntity<?> save(Authentication authentication, Principal principal, #PathVariable Integer id, #RequestBody UserNewDTO dto) {
........
}
You may find more details from here and from this blog
This link explains everything about JWT authentication.
Below you can see some examples could be used as base to adapt your code:
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api/test")
public class TestController {
#GetMapping("/all")
public String allAccess() {
return "Public Content.";
}
#GetMapping("/user")
#PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public String userAccess() {
return "User Content.";
}
#GetMapping("/mod")
#PreAuthorize("hasRole('MODERATOR')")
public String moderatorAccess() {
return "Moderator Board.";
}
#GetMapping("/admin")
#PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return "Admin Board.";
}
}
I am mostly using JWT authentication and spring security together in my web applications. Here is my common practice shortly:
Verify JWT token(or query from your token store)
private Claims getClaimsFromToken(String token, String key) throws ServletException {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token)
.getBody();
Fetch user to be authenticated and its authorities(or role in your case) who owns the token.
User user = getUserFromToken(token);
List<GrantedAuthority> authorities = getGrantedAuthorities(user);
public List<GrantedAuthority> getGrantedAuthorities(User user) {
List<GrantedAuthority> result = new ArrayList<>();
for (String privilegeName : user.getAuthorities()){ // e.g. ["READ", "WRITE"]
result.add(new SimpleGrantedAuthority(privilegeName));
}
return result;
}
Create org.springframework.security.authentication.AbstractAuthenticationToken
with your user and its authorities and inject into SecurityContextHolder.
AuthenticationFilter.java:
JWTAuthenticationToken jwtAuthenticationToken = new JWTAuthenticationToken(user,
authorities);
JWTAuthenticationToken.java
public class JWTAuthenticationToken extends AbstractAuthenticationToken {
private User user;
public JWTAuthenticationToken(User user, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.user = user;
}
Use #PreAuthorize with required authority for user can access.
#PreAuthorize("hasAnyAuthority('READ')")
Get user from SecurityContextHolder if necesseray.
User User= SecurityContextHolder.getContext().getAuthentication().getUser();
Have you tried:
#PreAuthorize ("hasRole('ROLE_ADMIN')")
Edit:
To check if the user is assigned to more than one role use:
#PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
You can implement your own AbstractPreAuthenticatedProcessingFilter and create your principal yourself.
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
final String token = request.getHeader("YOUR_HEADER");
DecodedJWT jwt = JWT.decode(token);
// TODO create principal
}

Jwt token gets invalidated on each restart of spring boot application

I have a spring boot application which generates a jwt token on successful login. and the token is returned to the user, but on each restart of the application the token is invalidated. I have a secret key stored on the properties file for now to test. here is my code to generate it,
public String createToken(String username, String role) {
Claims claims = Jwts.claims().setSubject(username);
claims.put("auth", role);
claims.put("test", "test");
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()//
.setClaims(claims)//
.setIssuedAt(now)//
.setExpiration(validity)//
.signWith(SignatureAlgorithm.HS256, secretKey)//
.compact();
}
I would like to have the token validated even though the application is restarted. Any suggestions on what I could be doing wrong is appreciated.
My Config class
public class JwtTokenFilterConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private JwtTokenProvider jwtTokenProvider;
public JwtTokenFilterConfigurer(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
#Override
public void configure(HttpSecurity http) throws Exception {
JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}

How to pass custom creds to spring boot ldap

I'm using a combination of spring-ldap and spring-boot-starter security. I have configured the basic setup but stuck at passing username and password to be authenticated. Its always trying to authenticate the default creds specified in the application.properties. Is there anyway to do this properly by passing the creds given in the login form.
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
if(Boolean.parseBoolean(ldapEnabled)) {
auth
.ldapAuthentication()
.contextSource()
.url(ldapUrls + ldapBaseDn)
.managerDn(ldapSecurityPrincipal)
.managerPassword(ldapPrincipalPassword)
.and()
.userDnPatterns(ldapUserDnPattern);
}
}
ldap.urls= ldap://localhost:10389/
ldap.base.dn= ou=users,dc=example,dc=com
ldap.username= cn=test, ou=users,dc=example,dc=com
ldap.user.dn.pattern = cn={0}
ldap.partitionSuffix=dc=example,dc=com
ldap.partition=example
ldap.principal=uid=admin,ou=system
ldap.password=secret
ldap.port=10389
ldap.url=ldap://localhost:10389/
I was able to fix this by using creating a bean that returns the user details context mapper as below.
#Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new LdapUserDetailsMapper() {
#Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
UserDetails details = super.mapUserFromContext(ctx, username, authorities);
return details;
}
};
}

Resources