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












0















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.



enter image description here



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.










share|improve this question























  • Why are you searching by username and password? You should search by username only.

    – Zmur
    Nov 27 '18 at 9:25











  • and then comparing passwords in authenticate() method?

    – Alexander Mujirishvili
    Nov 27 '18 at 10:44
















0















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.



enter image description here



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.










share|improve this question























  • Why are you searching by username and password? You should search by username only.

    – Zmur
    Nov 27 '18 at 9:25











  • and then comparing passwords in authenticate() method?

    – Alexander Mujirishvili
    Nov 27 '18 at 10:44














0












0








0








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.



enter image description here



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.










share|improve this question














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.



enter image description here



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.







java spring-mvc spring-security






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 27 '18 at 9:18









Alexander MujirishviliAlexander Mujirishvili

8517




8517













  • Why are you searching by username and password? You should search by username only.

    – Zmur
    Nov 27 '18 at 9:25











  • and then comparing passwords in authenticate() method?

    – Alexander Mujirishvili
    Nov 27 '18 at 10:44



















  • Why are you searching by username and password? You should search by username only.

    – Zmur
    Nov 27 '18 at 9:25











  • and then comparing passwords in authenticate() method?

    – Alexander Mujirishvili
    Nov 27 '18 at 10:44

















Why are you searching by username and password? You should search by username only.

– Zmur
Nov 27 '18 at 9:25





Why are you searching by username and password? You should search by username only.

– Zmur
Nov 27 '18 at 9:25













and then comparing passwords in authenticate() method?

– Alexander Mujirishvili
Nov 27 '18 at 10:44





and then comparing passwords in authenticate() method?

– Alexander Mujirishvili
Nov 27 '18 at 10:44












2 Answers
2






active

oldest

votes


















0














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();





share|improve this answer































    -1














    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
    }





    share|improve this answer



















    • 1





      can't find super.authenticate method...

      – Alexander Mujirishvili
      Nov 27 '18 at 10:41











    • Try to extend one of AuthenticationProvider interface implementations.

      – Zmur
      Nov 27 '18 at 10:51











    • which one for example?

      – Alexander Mujirishvili
      Nov 27 '18 at 10:52











    • 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.

      – Zmur
      Nov 27 '18 at 10:55








    • 1





      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);

      – Alexander Mujirishvili
      Nov 28 '18 at 12:52











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53496272%2fsecuritycontextholder-getcontext-getauthentication-getcredentials-returns%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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();





    share|improve this answer




























      0














      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();





      share|improve this answer


























        0












        0








        0







        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();





        share|improve this answer













        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();






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 28 '18 at 12:55









        Alexander MujirishviliAlexander Mujirishvili

        8517




        8517

























            -1














            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
            }





            share|improve this answer



















            • 1





              can't find super.authenticate method...

              – Alexander Mujirishvili
              Nov 27 '18 at 10:41











            • Try to extend one of AuthenticationProvider interface implementations.

              – Zmur
              Nov 27 '18 at 10:51











            • which one for example?

              – Alexander Mujirishvili
              Nov 27 '18 at 10:52











            • 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.

              – Zmur
              Nov 27 '18 at 10:55








            • 1





              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);

              – Alexander Mujirishvili
              Nov 28 '18 at 12:52
















            -1














            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
            }





            share|improve this answer



















            • 1





              can't find super.authenticate method...

              – Alexander Mujirishvili
              Nov 27 '18 at 10:41











            • Try to extend one of AuthenticationProvider interface implementations.

              – Zmur
              Nov 27 '18 at 10:51











            • which one for example?

              – Alexander Mujirishvili
              Nov 27 '18 at 10:52











            • 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.

              – Zmur
              Nov 27 '18 at 10:55








            • 1





              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);

              – Alexander Mujirishvili
              Nov 28 '18 at 12:52














            -1












            -1








            -1







            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
            }





            share|improve this answer













            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
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 27 '18 at 9:38









            ZmurZmur

            69212




            69212








            • 1





              can't find super.authenticate method...

              – Alexander Mujirishvili
              Nov 27 '18 at 10:41











            • Try to extend one of AuthenticationProvider interface implementations.

              – Zmur
              Nov 27 '18 at 10:51











            • which one for example?

              – Alexander Mujirishvili
              Nov 27 '18 at 10:52











            • 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.

              – Zmur
              Nov 27 '18 at 10:55








            • 1





              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);

              – Alexander Mujirishvili
              Nov 28 '18 at 12:52














            • 1





              can't find super.authenticate method...

              – Alexander Mujirishvili
              Nov 27 '18 at 10:41











            • Try to extend one of AuthenticationProvider interface implementations.

              – Zmur
              Nov 27 '18 at 10:51











            • which one for example?

              – Alexander Mujirishvili
              Nov 27 '18 at 10:52











            • 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.

              – Zmur
              Nov 27 '18 at 10:55








            • 1





              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);

              – Alexander Mujirishvili
              Nov 28 '18 at 12:52








            1




            1





            can't find super.authenticate method...

            – Alexander Mujirishvili
            Nov 27 '18 at 10:41





            can't find super.authenticate method...

            – Alexander Mujirishvili
            Nov 27 '18 at 10:41













            Try to extend one of AuthenticationProvider interface implementations.

            – Zmur
            Nov 27 '18 at 10:51





            Try to extend one of AuthenticationProvider interface implementations.

            – Zmur
            Nov 27 '18 at 10:51













            which one for example?

            – Alexander Mujirishvili
            Nov 27 '18 at 10:52





            which one for example?

            – Alexander Mujirishvili
            Nov 27 '18 at 10:52













            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.

            – Zmur
            Nov 27 '18 at 10:55







            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.

            – Zmur
            Nov 27 '18 at 10:55






            1




            1





            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);

            – Alexander Mujirishvili
            Nov 28 '18 at 12:52





            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);

            – Alexander Mujirishvili
            Nov 28 '18 at 12:52


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53496272%2fsecuritycontextholder-getcontext-getauthentication-getcredentials-returns%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)