Update User's first name and last name in principal

此生再无相见时 提交于 2020-05-14 10:22:28

问题


I am updating user's information like first name and last name and I am getting first name and last name in all the pages for welcome message.

I have two controllers one for ajax request mapping and the other for normal request mapping.

Normal request mapping controller have this method. In this controller all page navigation is present and some request mapping which are not ajax calls

private String getPrincipalDisplay() {
    GreenBusUser user = null;
            String userName = "";
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            if (principal instanceof UserDetails) {
                user = (GreenBusUser) principal;
                userName = user.getFirstName() + " " + user.getLastName();
            } else {
                userName = "";
            }
            return userName;
}

This is how I am getting the username on every page by return string of this function I am adding it in ModelMap object.

When I update user's information I am doing in ajax request mapping.

@RequestMapping(value = "/restify/updateUserData",  method = RequestMethod.PUT, headers = "Accept=application/json")
    public ServiceResponse forgotPassword(@RequestBody Object user)
    {   
        //logger.debug("getting response");
        return setDataPut("http://localhost:7020/forgotPassword",user);
    } 

user is an Object type which has json data. Now how do I retrieve data from object and update my first name and last name in principal.

This is my GreenBusUser class

public class GreenBusUser  implements UserDetails
{
    private static final long serialVersionUID = 1L;
    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> grantedAuthorities;

    private String firstName;

    private String lastName;

    public GreenBusUser(String username,String password,Collection<? extends GrantedAuthority>  authorities,String firstName, String lastName)
    {
        this.username = username;
        this.password = password;
        this.grantedAuthorities = authorities;
        this.firstName=firstName;
        this.lastName=lastName;

        this.grantedAuthorities.stream().forEach(System.out::println);

    }

    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        return grantedAuthorities;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getPassword()
    {
        return password;
    }

    public String getUsername()
    {
        return username;
    }

    public boolean isAccountNonExpired()
    {
        return true;
    }

    public boolean isAccountNonLocked()
    {
        return true;
    }

    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    public boolean isEnabled()
    {
        return true;
    }
}

UPDATE:::::

I have updated your code and applied some part of your answer into mine but still I ran into a problem

@RequestMapping(value="/updateUser",method=RequestMethod.GET)
    public String updateUser(ModelMap model) {

        UserInfo user = getUserObject();
        GreenBusUser newGreenBususer = null;
        List<User> list = new ArrayList<User>();


        list = FetchDataService.fetchDataUser("http://localhost:8060/GetuserbyUserName?username=" + getPrincipal(), user.getUsername(), user.getPassword());
        logger.debug("new user list ----->>>"+list.size());
        User newuser=(User)list.get(0);
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                   SecurityContextHolder.getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext().getAuthentication().getCredentials());

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        newGreenBususer=(GreenBusUser)principal;

        logger.debug("newGreenBususerDetails---->>>"+newGreenBususer.toString());

        newGreenBususer.setFirstName(newuser.getFirstName());
        newGreenBususer.setLastName(newuser.getLastName());

        if(newGreenBususer.getFirstName()!=null) {
            logger.debug("got my first name");
        }
        if(newGreenBususer.getLastName()!=null) {
            logger.debug("got my last name");
        }

        auth.setDetails(newGreenBususer);       
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(auth);
        SecurityContextHolder.setContext(context);
        model.addAttribute("user", getPrincipalDisplay());
        model.addAttribute("userData", list);
        model.addAttribute("check", true);
        return "GreenBus_updateProfile_User";
    }

At first it sets the firstname and lastname to GreenBusUser and then there is setDetails method when I reload the page it says No user found when I am calling getUserObject() method at the top of this method.

private X2CUser getUserObject() {
        X2CUser userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((X2CUser) principal);
        } else {
            logger.info("No user found");

        }
        return userName;
    }

回答1:


If you are updating the password, then it will be good to logout the user and tell him to relogin.




回答2:


Try this code .. It might help you.

UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);



回答3:


I have finally resolved my problem though I have later added some code in my question part in UPDATE section.

 Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        newGreenBususer=(GreenBusUser)principal;


        newGreenBususer.setFirstName(newuser.getFirstName());
        newGreenBususer.setLastName(newuser.getLastName());

Yes that's all need to be done.

This part--->>

    auth.setDetails(newGreenBususer);       
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);

set new context making security pointing to null when I reload still not clear because I am setting the details before reload so its like I get new context but I have set the new user details.

Though I have finally resolved my problem but if anyone could shed some light why it was happening then I will accept his/her answer.

Thanks alot for your support. Keep Learning!



来源:https://stackoverflow.com/questions/50621118/update-users-first-name-and-last-name-in-principal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!