java - 使用spring security成功登录后如何将对象添加到 View 中?

标签 java spring-boot authentication spring-security thymeleaf

成功登录后,我尝试重定向到需要实例化对象的页面,如我的 HomeController 中所述:

@RequestMapping(value={"/","/home"}, method=RequestMethod.GET)
public ModelAndView home() {
    ModelAndView view = new ModelAndView("home");
    view.addObject("client", new Client());
    return view;
}

问题是我不知道如何使用 Spring Security 来做到这一点,因为我唯一能做的设置就是在成功登录后设置页面:

.formLogin()
    .loginPage("/login")
    .defaultSuccessUrl("/home")
    .permitAll()

使用 Spring Security 成功登录后如何将此对象添加到 View 中?

最佳答案

假设您有这样的 WebSecurity 配置。您只需要添加一个 successHandler

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private SimpleAuthenticationSuccessHandler successHandler;

    @Bean("authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
        auth.inMemoryAuthentication()
            .withUser("user1").password("{noop}user1Pass").roles("USER")
            .and()
            .withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
        // @formatter:on
    }


    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/anonymous*").anonymous()
            .antMatchers("/login*").permitAll()
            .anyRequest().authenticated()

            .and()
            .formLogin()
            .loginPage("/login.html")
            .loginProcessingUrl("/login")
            .successHandler(successHandler)
            // ...        
    }
}

SimpleAuthenticationSuccessHandler 类

// Change onAuthenticationSuccess logic as per your requirement

@Component
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication authentication)
            throws IOException, ServletException {


        redirectStrategy.sendRedirect(arg0, arg1, "/home");


        /*
        Collectionextends GrantedAuthority> authorities = authentication.getAuthorities();
        authorities.forEach(authority -> {
            if(authority.getAuthority().equals("ROLE_USER")) {
                try {
                    redirectStrategy.sendRedirect(arg0, arg1, "/user");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if(authority.getAuthority().equals("ROLE_ADMIN")) {
                try {
                    redirectStrategy.sendRedirect(arg0, arg1, "/admin");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                throw new IllegalStateException();
            }
        });

        */


    }

}

这会将您的调用重定向到“/home”, Controller 将进一步负责加载您的对象。

更多详细信息here

关于java - 使用spring security成功登录后如何将对象添加到 View 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58050715/

相关文章:

java - Spring Boot - 可以拦截@Async 服务方法吗?

Xamarin Forms 登录按钮动画

json - Swift - 具有基本身份验证的 Http-Request

java - 使用 For 循环生成多个字符串

java - 追加到 java.library.path 中 `jvmArguments` 的某个路径

java - 如何在 java spring boot 中将字节数组作为内存文件返回?

symfony - 如何检查用户是否在 Controller 内登录 Symfony2?

java - NamedParameterJdbcTemplate.batchUpdate() 采用 Map<String,Object> 数组,如何实例化参数数组以免收到警告?

java - 运行集成测试时如何将 Grails 作为 Web 应用程序启动

java - 如何在标签上设置整数值?