SecurityContextHolder.getContext().getAuthentication().getCredentials() returns null after authentication

securitycontextholder getcontext getauthentication returning anonymous
securitycontextholder getcontext getauthentication returns null junit
spring security custom principal
spring security get user role in controller
spring security get all logged in users
securitycontextholder getcontext setauthentication
authentication getdetails is null
authenticationprincipal spring boot

I have created a simple spring web mvc app and I have one problem. After authentication I try to get an authentication object and for some reason it's credentials is null.

In this project I have a custom AuthenticationProvider which looks like this:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @PostConstruct
    public void init() {
        roleService.AddStandardRolesIfNeeded();
        userService.AddUserWithAdminRoleIfNotExists("a"); 
    }


    public Authentication authenticate(Authentication authentication) throws AuthenticationException {


        Object credentials = authentication.getCredentials();
        if(!(credentials instanceof String)) {
            return null;
        }

        String username = authentication.getName();
        String password = credentials.toString(); //password isn't null here


        User user = userService.findByUsernameAndPassword(username, password);


        if(user == null) {
            throw new BadCredentialsException("Authentication failed for " + username);
        }


        List<GrantedAuthority> authorities = new ArrayList<>();
        for(Role role : user.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        Authentication auth = new 
                UsernamePasswordAuthenticationToken(username, password, authorities);


        return auth;
    }

    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

I am interested in if it is intentionally done in spring security or I am missing something.

Because the credentials will be deleted after authentication is successful, you must add eraseCredentials(false) to AuthenticationManagerBuilder configuration. Like the code bellow:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthProvider).eraseCredentials(false);
}

This is late, but I think this is the correct answer according to the question.

org.springframework.security.core.Authentication.getCredentials , getContext() .getAuthentication(); if (authentication == null) { log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials");  After authentication I try to get an authentication object and for some reason it's credentials is null. .getAuthentication().getCredentials() returns null after

I solved this by passing user object to UsernamePasswordAuthenticationToken constructor instead of username in place of principal.

I changed this:

Authentication auth = new 
                UsernamePasswordAuthenticationToken(username, password, authorities);

to this:

Authentication auth = new 
                    UsernamePasswordAuthenticationToken(user, password, authorities);

And in controller I get the user so:

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Spring Security's authentication.getName returns null in controller , Im using spring boot 2.0 with OAuth so I'm doing it like this Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Object pricipal = auth. Spring Security: SecurityContextHolder.getContext().getAuthentication() returns null after user registering user and redirecting to after login page 1 Spring boot security cannot log in after invalid credentials

Authentication should be made more like so:

@Override
public Authentication authenticate(final Authentication authentication) {
    //better to use optionals with repositories, they greatly reduce NullPointer exception quantity
    final SomeUser user = UserRepository.findByUsernameIgnoreCase(authentication.getName())
                .orElseThrow(() -> new UsernameNotFoundException("some message"));
    try {
            final Authentication auth = super.authenticate(authentication);
            //can add logic here, such as login time recording
            return auth;
    } catch (...) {
           //handle various exceptions here, for example failed login attempts and user locking
    }

Retrieve User Information in Spring Security, getContext().getAuthentication();. String currentPrincipalName = authentication.​getName();. An improvement to this snippet is first checking if  The AuthenticationManager implementation will often return an Authentication containing richer information as the principal for use by the application. Many of the authentication providers will create a UserDetails object as the principal. Returns: the Principal being authenticated or the authenticated principal after authentication.

SecurityContextHolder.getContext().getAuthentication() returning null, is null springboot securitycontextholder.getcontext().getauthentication() returns null spring boot authentication getcredentials returns null. I want to getAuthentication() becoming null after redirect is correct since it is threadbound. Used to indicate to AbstractSecurityInterceptor whether it should present the authentication token to the AuthenticationManager.Typically an AuthenticationManager (or, more often, one of its AuthenticationProviders) will return an immutable authentication token after successful authentication, in which case that token can safely return true to this method.

Authentication (spring-security-docs-manual 5.3.3.RELEASE API), Never null. getCredentials. java.lang.Object getCredentials(). The credentials that prove the principal is correct. This is usually a  For example, if I am using the authentication for Authorization (@PreAuthorize("@validator.isAuthorised(true,#request,authentication)")) on rest end points to determine the access will it be safe? This comment has been minimized.

6. Technical Overview, In particular, there is no need to configure a special Java Authentication and is taken to clear the thread after the present principal's request is processed. The object returned by the call to getContext() is an instance of the SecurityContext getCredentials())) { return new UsernamePasswordAuthenticationToken(auth. SecurityContextHolder.getContext().getAuthenticati on() returns null Hi, I am trying to use SecurityContextHolder.getContext().getAuthenticati on() to check if the authentication has been done. On the basis of this discussion, I want to display/not display

Comments
  • Why are you searching by username and password? You should search by username only.
  • and then comparing passwords in authenticate() method?
  • I have tried this several times with this config, its not working for me, getCredentials() returns null
  • Try to extend one of AuthenticationProvider interface implementations.
  • which one for example?
  • In my project I used as example, a DaoAuthenticationProvider is extended. But take time and read their docs, perhaps you will find another one better suited for you.
  • I can not use DaoAuthenticationProvider or any other that needs to define UserDetailsService, so I solved this problem by passing user object instead of username string in this line UsernamePasswordAuthenticationToken(username, password, authorities);