I have a UserController that receives a UserDTO and creates/updates the user in the DB. The problem I'm getting is that I also have a login, and when I insert the username and password on the login form, I always get the 'Wrong Password.' exception, despite the credentials being correctly inserted.
One thing I suspect is that BCrypt is to blame, since due to the fact that it generates random salt while encoding, maybe, just maybe, the cipher text ends up being different and stuff, which is weird, since I assume that it should work. I want to know how can I fix this problem of the hashing being different & not being able to validate the userCredentials
I have tried for example encoding the received password and using the matches method via my autowired passwordEncoder, and I'm using my own authProvider.
Here's the code, let me know if you need anything else.
CustomAuthProvider.java
#Service
public class CustomAuthProvider implements AuthenticationProvider {
private final UserServiceImpl userServiceImpl;
private final BCryptPasswordEncoder passwordEncoder;
#Autowired
public CustomAuthProvider(UserServiceImpl userServiceImpl, BCryptPasswordEncoder passwordEncoder) {
this.userServiceImpl = userServiceImpl;
this.passwordEncoder = passwordEncoder;
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails userDetails = userServiceImpl.loadUserByUsername(username);
if (!passwordEncoder.matches(password, userDetails.getPassword())) { //The problem is here evidently.
throw new BadCredentialsException("Wrong password.");
}
return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
Also, here's the loadUserByUsername method:
UserServiceImpl.java
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDTO user = this.getUserByUsername(username);
User anUser = convertToUser(user);
ModelMapper modelMapper = new ModelMapper();
return modelMapper.map(anUser,UserPrincipal.class);
}
}
And here is the save method I use to save and update users, as well as the LoginController;
#Override
public void save(UserDTO user) {
User aUser = this.convertToUser(user);
aUser.setPassword(passwordEncoder.encode(aUser.getPassword()));
this.userRepository.save(aUser); }
LoginController.java:
#RestController
public class LoginController{
private final CustomAuthProvider providerManager;
#Autowired
public LoginController(CustomAuthProvider providerManager) {
this.providerManager = providerManager;
}
#GetMapping("/login")
public String login() {
return "login";
}
#PostMapping("/login")
public String login(#RequestParam("username") #NotBlank String username,
#RequestParam("password") #NotBlank String password, Model model) {
if(username == null || password == null) { //This is probably not necessary
model.addAttribute("error", "Invalid credentials");
return "login";
}
try {
Authentication auth = providerManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
SecurityContextHolder.getContext().setAuthentication(auth);
return "redirect:/notes";
} catch (AuthenticationException e) {
model.addAttribute("error", "Invalid credentials");
return "login";
}
}
}
UserPrincipal.java
#Data
public class UserPrincipal implements Serializable , UserDetails {
int id;
private String username;
private String password;
private Date accountCreationDate = new Date();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
#Override
public boolean isAccountNonExpired() {
return false;
}
#Override
public boolean isAccountNonLocked() {
return false;
}
#Override
public boolean isCredentialsNonExpired() {
return false;
}
#Override
public boolean isEnabled() {
return false;
}
}
UserDTO.java
#Data
public class UserDTO implements Serializable {
int id;
private String username;
private String password;
private List<Note> notes = new ArrayList<>();
}
I read several issues related to this topic, like
Spring Boot PasswordEncoder.matches always false
Spring Security - BcryptPasswordEncoder
Inconsistent hash with Spring Boot BCryptPasswordEncoder matches() method
How can bcrypt have built-in salts?
Decode the Bcrypt encoded password in Spring Security to deactivate user account
but none of those helped me solve my issue and there was no real solution to the problem since most of them don't even have an accepted answer.
EDIT: Found out that the 'matches' method only works if I insert the hashed password, not the raw password.
Found out my mistake:
The setPassword method in the User class was re-hashing the hashed password which was already being hashed on the save method, thus the modelMapper.map() method used that setPassword method, therefore the passwords never matched and the password I got from the user class never matched the actual password I could see on my database.
Related
I'm creating an api for use in a pharmacy. When implementing the security, jwt token and filter for using security, an error occurs when validating requests and the token is simply not considered valid. It has an expiration time of 2 hours, the user is allowed to login, I do this via postman, I take the token that appears, I copy and paste it in the authorization validation, I make a protected request in postman and I simply take a forbidden403 . I'm using the post method to make this request, and the baerer Token to send it. In the code, as you can see, it has all the correct configuration for my filter to come before spring's filter and also has the configuration to demonstrate how far the code is running, with a sistem.out with the message("calling filter") What indicates that the code runs until the validation of the token and after the problem. Note: I'm using mysql, springboot 3.0 and java 17. The entire structure of the tables is already created and working, but I can't make any request besides the login after facing this validation error. Follow the code below:
User Entity: #Table(name = "users") #Entity(name = "User") #Getter #NoArgsConstructor #AllArgsConstructor
#EqualsAndHashCode(of ="id") public class User implements UserDetails{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String login;
private String senha;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_USER"));
}
#Override
public String getPassword() {
return senha;
}
#Override
public String getUsername() {
return login;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Authentication Controller:
#RestController #RequestMapping("/login") public class AutenticacaoController {
#Autowired
private AuthenticationManager manager;
#Autowired
private TokenService tokenService;
#PostMapping
public ResponseEntity<DadosTokenJWT> efetuarLogin(#RequestBody #Valid DadosAutenticacao dados) {
var authenticationToken = new UsernamePasswordAuthenticationToken(dados.login(), dados.senha());
var authentication = manager.authenticate(authenticationToken);
var tokenJWT = tokenService.gerarToken((Usuario) authentication.getPrincipal());
return ResponseEntity.ok(new DadosTokenJWT(tokenJWT));
}
}
SecutiryConfigurations:
#Configuration #EnableWebSecurity public class SecutiryConfigurations {
#Autowired
private SecutiryFilter securityFilter;
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
return http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeHttpRequests().requestMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and().addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception{
return configuration.getAuthenticationManager();
}
#Bean
public PasswordEncoder passwordEncoder () {
return new BCryptPasswordEncoder();
}
}
Token Service:
#Service public class TokenService {
#Value("${api.security.token.secret}")
private String secret;
public String gerarToken(Usuario usuario) {
try {
var algoritmo = Algorithm.HMAC256(secret);
return JWT.create().withIssuer("API remedios_api").withSubject(usuario.getLogin())
.withExpiresAt(dataExpiracao()).sign(algoritmo);
} catch (JWTCreationException exception) {
throw new RuntimeException("Erro ao gerar Token JWT", exception);
}
}
public String getSubject(String tokenJWT) {
try {
var algoritmo = Algorithm.HMAC256(secret);
return JWT.require(algoritmo).withIssuer("API remedios_api").build().verify(tokenJWT).getSubject();
} catch (JWTVerificationException exception) {
throw new RuntimeException("Token inválido ou expirado");
}
}
private Instant dataExpiracao() {
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
}
}
SecurityFilter:
#Component public class SecutiryFilter extends OncePerRequestFilter{
#Autowired
private TokenService tokenService;
#Autowired
private UsuarioRepository repository;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
var tokenJWT = recuperarToken(request);
System.out.println("Chamando Filter");
if(tokenJWT != null) {
var subject = tokenService.getSubject(tokenJWT);
var usuario = repository.findByLogin(subject);
var authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
System.out.println("Logado na requisição");
}
filterChain.doFilter(request, response);
}
private String recuperarToken(HttpServletRequest request) {
var authorizationHeader = request.getHeader("Authorization");
if( authorizationHeader != null) {
return authorizationHeader.replace("Bearer", "");
}
return null;
}
I login via postman, get the token code and paste it in the authorization to then use that token in some other request that is also protected via spring security.
I hope the request is accepted and released after validating the token in the request header.
I'm trying to integrate the updated Spring Security in my project, instead of using the deprecated extending WebSecurityConfigurerAdapter. I've set up a good system in which the user gets authenticated (User implements UserDetails - I am using Hibernate) and a token gets generated. I get a 200 on this login and receive a token. This authetication part works fine.
Now the problem is that my users have roles (like ADMIN, USER, ...) These roles are added to the generated token. My controllers get the #PreAuthorize annotation. The request cannot pass these annotation and get a forbidden. When I don't use the #PreAuthorize, the requests get validated with the token.
#Configuration
#EnableWebSecurity
#EnableMethodSecurity
public class SecurityConfig {
private RSAKey rsaKey;
private final DefaultUserDetailsService defaultUserDetailsService;
public SecurityConfig(DefaultUserDetailsService defaultUserDetailsService) {
this.defaultUserDetailsService = defaultUserDetailsService;
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
)
.userDetailsService(defaultUserDetailsService)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.headers(headers -> headers
.frameOptions().sameOrigin()
)
.httpBasic(withDefaults())
.build();
}
#Bean
public JWKSource<SecurityContext> jwkSource() {
rsaKey = Jwks.generateRsa();
JWKSet jwkSet = new JWKSet(rsaKey);
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
}
#Bean
JwtDecoder jwtDecoder() throws JOSEException {
return NimbusJwtDecoder.withPublicKey(rsaKey.toRSAPublicKey()).build();
}
#Bean
JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwks) {
return new NimbusJwtEncoder(jwks);
}
#Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:4200"));
configuration.setAllowedMethods(List.of("GET","POST","DELETE"));
configuration.setAllowedHeaders(List.of("Authorization","Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",configuration);
return source;
}
}
#Component
public class KeyGeneratorUtils {
private KeyGeneratorUtils() {}
static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
keyPair = keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
}
public class Jwks {
private Jwks() {}
public static RSAKey generateRsa() {
KeyPair keyPair = KeyGeneratorUtils.generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build();
}
}
#Service
public class DefaultTokenService implements TokenService {
private final JwtEncoder encoder;
public DefaultTokenService(JwtEncoder encoder) {
this.encoder = encoder;
}
#Override
public String generateToken(Authentication authentication) {
Instant now = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
System.out.println("scope: " + scope);
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(1, ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope", scope)
.build();
return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
}
public class UserDetailsImpl implements UserDetails{
private static final long serialVersionUID = 1L;
private final Long id;
private final String username;
private final String riziv;
private final boolean verified;
#JsonIgnore
private final String password;
private final Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(Long id, String username, String riziv, String password,
Collection<? extends GrantedAuthority> authorities, boolean verified) {
this.id = id;
this.username = username;
this.riziv = riziv;
this.password = password;
this.authorities = authorities;
this.verified = verified;
}
public static UserDetailsImpl build(AuthUser authUser) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(authUser.getRol().toString()));
return new UserDetailsImpl(
authUser.getId(),
authUser.getUsername(),
authUser.getRiziv(),
authUser.getPassword(),
authorities, authUser.isVerified());
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public Long getId() {
return id;
}
public boolean isVerified() {
return verified;
}
public String getRiziv() {
return riziv;
}
#Override
public String getUsername() {
return username;
}
#Override
public String getPassword() {
return password;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl klant = (UserDetailsImpl) o;
return Objects.equals(id, klant.id);
}
}
#Service
public class DefaultUserDetailsService implements UserDetailsService {
private final AuthUserService authUserService;
public DefaultUserDetailsService(AuthUserService authUserService) {
this.authUserService = authUserService;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AuthUser authUser = authUserService.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(authUser);
}
}
#PreAuthorize("hasAnyRole('USER', 'ADMIN')")
I am making a configuration mistake somewhere, but I cannot seem to find it. Spring docs are very very hard to figure out, but I have been reading them relentlessly. There is also not a lot of clear information on these topics yet. I can find youtube videos tutorials and some related topics, but they only explain small parts, never a full setup.
I have added below my securityConfig, KeyGenerator, Jwks and tokengenerate service. I also just added the Userdetailsimpl and service. I build my userdetailsImpl out of a user with a static build method. It might seem a strange construction but it works, it is because I did the security last and didn't think of it before. Also I added an example of my #Preauthorize.
I am very close and this could be a good example for other users trying to implement this, because I seem not te able to find an example somewhere.Does anyone have experience with setting the Spring Boot 3 security up and can they tell me how I am misconfiguring? Why is my role not getting 'read' by the #PreAuthorize?
Okay so here's the thing, since you're implementing resource server, the class
org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
is the one responsible for converting your scopes inside jwt token to granted authorities.
Now, this class prepends all the authorities with SCOPE_ prefix.
Since you're using
hasAnyRole('ADMIN', 'USER',...)
this method internally invokes
hasAnyAuthorityName(defaultRolePrefix, roleName)
method with the defaultRolePrefix as ROLE_ and the roleName as your passed value(s).
Internal Implementation:
#Override
public final boolean hasAnyRole(String... roles) {
return hasAnyAuthorityName(this.defaultRolePrefix, roles);
}
#Override
public final boolean hasAnyAuthority(String... authorities) {
return hasAnyAuthorityName(null, authorities);
}
On the other hand, the hasAnyAuthority method makes a call to the same method but with null passed as defaultRolePrefix.
Now since you're using
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
in security config, it is using the default AuthenticationConverter for your jwt token which is
org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter
which further invokes
org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
As per the implementation in JwtGrantedAuthoritiesConverter, all the scopes in your jwt token are prefixed by SCOPE_ as I mentioned earlier.
Now assuming your granted authorities return ADMIN as one of the roles. Once you add it to your scope in jwt, the default converter will return SCOPE_ADMIN as an Authority and similarly if you return ROLE_ADMIN in the scope, it will be converted to SCOPE_ROLE_ADMIN by default.
The JwtAuthenticationConverter class returns an instance of
org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
So, it can be fixed in following ways:
Either, use hasAnyAuthority to check the authorities by appending SCOPE_ to the role names you have set in scope.
If your role name is ADMIN or ROLE_ADMIN you should use
#PreAuthorize("hasAnyAuthority('SCOPE_ADMIN')")
#PreAuthorize("hasAnyAuthority('SCOPE_ROLE_ADMIN')")
and so on.
If you want to use hasAnyRole check then you must use
#PreAuthorize("hasAnyAuthority('ROLE_SCOPE_ADMIN')")
#PreAuthorize("hasAnyAuthority('ROLE_SCOPE_ROLE_ADMIN')")
for ADMIN and ROLE_ADMIN values respectively.
Or, Implement a custom Authority Converter and pass it to the oauth2ResourceServer in security config as follows,
Example Custom Converter
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import java.util.Collections;
#Component
public class JwtCustomAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
#Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
Collection<String> splitScopes = Arrays.asList(jwt.getClaim("scope").split(" "));
for (String authority : splitScopes) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority));
}
return grantedAuthorities;
}
}
Then update your spring security config as:
#Bean
JwtCustomAuthoritiesConverter jwtCustomAuthoritiesConverter;
#Bean
JwtAuthenticationConverter jwtAuthenticationConverter(){
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtCustomAuthoritiesConverter);
return jwtAuthenticationConverter;
}
...
http.oauth2ResourceServer((oauth2) ->
oauth2.jwt((jwt) -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))
...
With the second option you can use your role names the way you want to in jwt token and the
hasAnyRole('ADMIN')
check should get ROLE_ADMIN for ADMIN scope instead of ROLE_SCOPE_ADMIN which is the case now.
I have the following two classes which provide the JWT authentication mechanisem.
CustomDelegatingAuthenticationProvider
#Singleton
#Replaces(value = DelegatingAuthenticationProvider.class)
public class CustomDelegatingAuthenticationProvider extends DelegatingAuthenticationProvider {
/**
* #param userFetcher Fetches users from persistence
* #param passwordEncoder Collaborator which checks if a raw password matches an encoded password
* #param authoritiesFetcher Fetches authorities for a particular user
*/
public CustomDelegatingAuthenticationProvider(UserFetcher userFetcher, PasswordEncoder passwordEncoder, AuthoritiesFetcher authoritiesFetcher) {
super(userFetcher, passwordEncoder, authoritiesFetcher);
}
#Override
protected Publisher<AuthenticationResponse> createSuccessfulAuthenticationResponse(AuthenticationRequest authenticationRequest, UserState userState) {
if (userState instanceof UserMember) {
UserMember user = (UserMember) userState;
return Flowable
.fromPublisher(authoritiesFetcher.findAuthoritiesByUsername(user.getUsername()))
.map(authorities -> new HDSUser(user.getUsername(), authorities, user.getId()));
}
return super.createSuccessfulAuthenticationResponse(authenticationRequest, userState);
}
}
CustomJWTClaimsSetGenerator
#Singleton
#Replaces(value = JWTClaimsSetGenerator.class)
public class CustomJWTClaimsSetGenerator extends JWTClaimsSetGenerator {
CustomJWTClaimsSetGenerator(TokenConfiguration tokenConfiguration, #Nullable JwtIdGenerator jwtIdGenerator, #Nullable ClaimsAudienceProvider claimsAudienceProvider) {
super(tokenConfiguration, jwtIdGenerator, claimsAudienceProvider);
}
protected void populateWithUserDetails(JWTClaimsSet.Builder builder, UserDetails userDetails) {
super.populateWithUserDetails(builder, userDetails);
if (userDetails instanceof HDSUser) {
builder.claim("userId", ((HDSUser) userDetails).getId());
}
}
}
The default response to the client looks like this:
My question. How can I extend the class to return all user attributes? Besides username I want to have the user id.
UPDATE
HDS user class which gathers the DB id
#CompileStatic
public class HDSUser extends UserDetails {
private long id;
public HDSUser(String username, Collection<String> roles, long id) {
super(username, roles);
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
To extend the returned data you need to extend (implement custom) TokenRenderer as well as a custom version of the AccessRefreshToken.
Just as a simple example see the following code snipped which will extend the default access token payload with userId field.
First, create a custom AccessRefreshToken class with additional fields which are required.
#Introspected
#Getter
#Setter
public class CustomAccessRefreshToken extends BearerAccessRefreshToken {
// the new field which will be in the response
private String userId;
public CustomAccessRefreshToken(String username,
Collection<String> roles,
Integer expiresIn,
String accessToken,
String refreshToken,
String tokenType
) {
super(username, roles, expiresIn, accessToken, refreshToken, tokenType);
}
}
Next, we will need a TokenRenderer which will be used by the underlying subsystem to generate our custom token.
#Singleton
#Replaces(value = BearerTokenRenderer.class)
public class CustomTokenRenderer implements TokenRenderer {
private static final String BEARER_TOKEN_TYPE = HttpHeaderValues.AUTHORIZATION_PREFIX_BEARER;
#Override
public AccessRefreshToken render(Integer expiresIn, String accessToken, #Nullable String refreshToken) {
return new AccessRefreshToken(accessToken, refreshToken, BEARER_TOKEN_TYPE, expiresIn);
}
#Override
public AccessRefreshToken render(Authentication authentication, Integer expiresIn, String accessToken, #Nullable String refreshToken) {
CustomAccessRefreshToken token = new CustomAccessRefreshToken(authentication.getName(), authentication.getRoles(), expiresIn, accessToken, refreshToken, BEARER_TOKEN_TYPE);
// here just take the user data from Authentication object or access any other service
token.setUserId("Some user id");
return token;
}
}
That's it )) Just implement render() method the way you want and add as many custom fields as needed.
The response from the given example will look like
{
"username": "sherlock",
"userId": "Some user id",
"access_token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzaGVybG9jayIsIm5iZiI6MTYzNjk5MTgzMSwicm9sZXMiOltdLCJpc3MiOiJtaWNyb25hdXRndWlkZSIsImV4cCI6MTYzNjk5NTQzMSwiaWF0IjoxNjM2OTkxODMxfQ.Cat1CTsUZkCj-OHGafiefNm1snPsALoaNw9y2xwF5Pw",
"token_type": "Bearer",
"expires_in": 3600
}
If you are on the older version of the Micronaut v1.x the TokenRenderer will look like this.
#Singleton
#Replaces(value = BearerTokenRenderer.class)
public class CustomTokenRenderer implements TokenRenderer {
private static final String BEARER_TOKEN_TYPE = HttpHeaderValues.AUTHORIZATION_PREFIX_BEARER;
public AccessRefreshToken render(Integer expiresIn, String accessToken, String refreshToken) {
return new AccessRefreshToken(accessToken, refreshToken, BEARER_TOKEN_TYPE, expiresIn);
}
public AccessRefreshToken render(UserDetails userDetails, Integer expiresIn, String accessToken, String refreshToken) {
CustomAccessRefreshToken token = new CustomAccessRefreshToken(userDetails.getUsername(), userDetails.getRoles(), expiresIn, accessToken, refreshToken, BEARER_TOKEN_TYPE);
token.setUserId("Some user id, Some user id");
return token;
}
}
I'm working REST API right now with Jersey, Spring. Which shall be accessed with an Android/iOS later.
If I have for example user settings like this #Path("/user/{userID}/settings") in a Jersey Resource. How can i ensure that every user can access his/her settings only? I have read a lot about spring-security-oauth2. But as far as i understand you can only verify that the user is really the user but not make a difference if he/she can access other users settings?!
What you need is called authorization.
Authorization can distingush level of accesses of each users.
It's major topic actually. You can use roles, permissions, ACL for securing the service.
The simplest way for solving your task is to use path /user/settings and find the authentication yourseft, like:
public Settings find() {
UserDetails customUserDetails = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return setingsService.findByUser(customUserDetails.getUsername());
}
Create your CustomUserDetails:
public class CustomUserDetails implements UserDetails {
private User user;
private Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(User user) {
this.user = user;
}
public User getUser() {
return user;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Authority authority : user.getAuthorities()) {
authorities.add(new SimpleGrantedAuthority(authority.getName()));
}
return authorities;
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getUsername();
}
// implement other methods
}
And CustomUserDetailsService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserService userService;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.findByUsername(username);
// check if exist
}
return new CustomUserDetails(user);
}
}
I am using Spring Security in my application. I need loggedIn user details in the controllers of my application.
For that I am using this code
User loggedInUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
But on running this code I get a classcastexception
java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to model.User
To fix this I referred to this article
Initially I used a CustomUserServiceDetails class
#Service("myUserDetailService")
#Transactional
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = Logger.getLogger(CustomUserDetailsService.class);
#Autowired
private UserDAO userDAO;
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
// returns the get(0) of the user list obtained from the db
User domainUser = userDAO.getUser(name);
logger.debug("User fetched from database in loadUserByUsername method " + domainUser);
Set<Role> roles = domainUser.getRole();
logger.debug("role of the user" + roles);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(Role role: roles){
authorities.add(new SimpleGrantedAuthority(role.getRole()));
logger.debug("role" + role + " role.getRole()" + (role.getRole()));
}
boolean credentialNonExpired = true;
return new org.springframework.security.core.userdetails.User(domainUser.getProfileName(), domainUser.getPassword(), domainUser.isAccountEnabled(),
domainUser.isAccountNonExpired(), credentialNonExpired, domainUser.isAccountNonLocked(),authorities);
}
}
But after referring to the article I removed the setting of GrantedAuthorities from here and moved it to my User class. Implemented spring-security UserDetails class in my User class
Now I have an extra property in my User class
#Entity
#Table(name = "user")
public class User implements UserDetails {
private Collection<GrantedAuthority> authorities;
with a setMethod
public void setAuthorities(Set<Role> roles) {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(Role role: roles){
authorities.add(new SimpleGrantedAuthority(role.getRole()));}
}
A. I am not sure how to map this property to the database. The existing User table schema doesn't contain a GrantedAuthority column besides It's not even a primitive type. I am using Hibernate for object mapping. Can anyone advice me the correct approach to obtain the user class info in the controllers?
B. I also considered the approach of extending the spring's User class and overloading the constructor of my User class. But then every time I initialize my User anywhere in the code I have to provide all the constructors parameters which is not good at all.
Instead of using
User loggedInUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
try this
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String username = loggedInUser.getName();
References:
https://www.mkyong.com/spring-security/get-current-logged-in-username-in-spring-security/
Fixed the issue
Solution
Created a CustomUserDetail class which implements Spring's UserDetails interface. Injected my model User class in it.
public class CustomUserDetail implements UserDetails{
private static final long serialVersionUID = 1L;
private User user;
Set<GrantedAuthority> authorities=null;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<GrantedAuthority> authorities)
{
this.authorities=authorities;
}
public String getPassword() {
return user.getPassword();
}
public String getUsername() {
return user.getProfileName();
}
public boolean isAccountNonExpired() {
return user.isAccountNonExpired();
}
public boolean isAccountNonLocked() {
return user.isAccountNonLocked();
}
public boolean isCredentialsNonExpired() {
return user.isCredentialsNonExpired();
}
public boolean isEnabled() {
return user.isAccountEnabled();
}
}
CustomUserServiceDetails
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO;
public CustomUserDetail loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
// returns the get(0) of the user list obtained from the db
User domainUser = userDAO.getUser(name);
Set<Role> roles = domainUser.getRole();
logger.debug("role of the user" + roles);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(Role role: roles){
authorities.add(new SimpleGrantedAuthority(role.getRole()));
logger.debug("role" + role + " role.getRole()" + (role.getRole()));
}
CustomUserDetail customUserDetail=new CustomUserDetail();
customUserDetail.setUser(domainUser);
customUserDetail.setAuthorities(authorities);
return customUserDetail;
}
}
In my controller method
CustomUserDetail myUserDetails = (CustomUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Integer userId=myUserDetails.getUser().getUserId(); //Fetch the custom property in User class
The method .getPrincipal() returns the object created and returned it in the method loadUserByUsername.
If you want an User you must return in the method loadUserByUsername an User, not an org.springframework.security.core.userdetails.User