简体   繁体   中英

how can I create a session on spring security from the backend?

I have my spring app with a login with spring security, it works fine, but I want to do something additional.

There are some users that will be logged throught another method, so, I will get a post with the data at my controllers... is there any way from that controller simulate that the user is actually entering his user/password at the login form and then create a session on spring security?

Right now I have this

Spring Securit Configuration

@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;
    }

Login method at my controller (nothing much really..)

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

        return mvc;
    }

I have my details service as well , like this

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

Any idea how to do this??

Thanks.

There is a way to do that. You can utilize Spring SecurityContextHolder. It would look something like this:

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

where principal is UserDetails object. If you don't have credentials, you can just pass null.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM