如何从后端创建Spring安全会话?

时间:2015-09-28 10:36:55

标签: java spring spring-security

我的春季应用程序带有弹簧安全登录,它工作正常,但我想做一些额外的事情。

有些用户会通过另一种方法登录,因此,我会在我的控制器上找到一个包含数据的帖子...是否有任何方法来自该控制器模拟用户实际输入他的用户/密码登录表单,然后创建一个关于spring security的会话?

现在我有了这个

Spring Securit配置

@Autowired
    private UserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/auth/**").authenticated();

        http.
                authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/admin/**")
                .access("hasRole('ROLE_ADMIN')")
                .antMatchers("/user/**")
                .access("hasRole('ROLE_USER')")
                .and()
                .formLogin()
                .defaultSuccessUrl("/usuario/home")
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/")
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        if(encoder == null) {
            encoder = new BCryptPasswordEncoder();
        }
        return encoder;
    }

我控制器的登录方法(真的没什么......)

 @RequestMapping("/login")
    public ModelAndView login() {
        ModelAndView mvc = new ModelAndView();
        mvc.setViewName("login");
        mvc.addObject("message", "");

        return mvc;
    }

我也有我的详细服务,就像这样

@Autowired
    private UserRepository userRepository;

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        com.jp.base.domain.User user = userRepository.findByUsername(username);
        List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
        System.out.println("user roles: " + user.getUserRoles());
        return buildUserForAuthentication(user, authorities);

    }

    private User buildUserForAuthentication(com.jp.base.domain.User user,
                                            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(), user.getPassword(), authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        return new ArrayList<GrantedAuthority>(setAuths);
    }
}

知道怎么做吗?

感谢。

2 个答案:

答案 0 :(得分:3)

有办法做到这一点。您可以使用Spring SecurityContextHolder。它看起来像这样:

UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, credentials);
SecurityContextHolder.getContext().setAuthentication(authentication);

其中principal是UserDetails对象。如果您没有凭据,则可以传递null。

答案 1 :(得分:0)

List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_USER");
grantedAuthorities.add(ga);

Authentication auth = new UsernamePasswordAuthenticationToken(user.getUid(), "", grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(auth);