Spring安全性从更深层访问UserDetailsS​​ervice [英] Spring security access UserDetailsService from deeper layers

查看:136
本文介绍了Spring安全性从更深层访问UserDetailsS​​ervice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下UserDetailsS​​ervice实现。

到目前为止,身份验证过程运行良好。

如何存储我的MyUser bean( 在会话中成功登录),以便我可以在我的应用程序的其他区域访问它


I have the following UserDetailsService implementation.
The authentication process is working great so far.
How do I store my "MyUser bean" (that logged in successfully ) in the "session" so i can get access to it in other areas in my application

谢谢。

@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {


    private EmployeesApi employeesApi = new EmployeesApi();

    /**
     * Retrieves a user record containing the user's credentials and access. 
     */
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException, DataAccessException {

        // Declare a null Spring User
        UserDetails user = null;

        try {


            MyUser employee = employeesApi.getByUserName(userName);



            user =  new User(
                    employee.getUserName(), 
                    employee.getPassword().toLowerCase(),
                    true,
                    true,
                    true,
                    true,
                    getAuthorities(1) );

        } catch (Exception e) {
            logger.error("Error in retrieving user");
            throw new UsernameNotFoundException("Error in retrieving user");
        }


    }
    ....


推荐答案

Spring Security已经为您在会话中存储了 UserDetails 经过身份验证的用户。

Spring Security already stores UserDetails of authenticated user in session for you.

因此,在会话中存储 MyUser 的最简单方法是实现包含的自定义 UserDetails MyUser 的引用:

So, the easiest way to store MyUser in session is to implement a custom UserDetails that contains a reference to MyUser:

public class MyUserDetails extends User {
    private MyUser myUser;
    public MyUserDetails(..., MyUser myUser) {
        super(...);
        this.myUser = myUser;
    }
    public MyUser getMyUser() {
        return myUser;
    }
    ...
}

并从你的 UserDetailsS​​ervice

MyUser employee = employeesApi.getByUserName(userName);
user =  new MyUserDetails(..., myUser);

然后您可以通过安全轻松访问 MyUser context:

Then you can easily access MyUser via security context:

MyUser myUser = ((MyUserDetails) SecurityContextHolder
    .getContext().getAuthentication().getPrincipal()).getMyUser();

在Spring MVC控制器中:

In Spring MVC controller:

@RequestMapping(...)
public ModelAndView someController(..., Authentication auth) {
    MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser();
    ...
}

在JSP中:

<security:authentication var = "myUser" property="principal.myUser" />

这篇关于Spring安全性从更深层访问UserDetailsS​​ervice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆