Custom WebAuthenticationDetails programmatically in spring security

混江龙づ霸主 提交于 2021-02-07 17:30:03

问题


I am currently moving from an xml-based configuration of spring security to a java based one. I need to setup a custom WebAuthenticationDetails via Java. Is there a way to do that? In XML, I would just set that authenticationDetailsSource of the UsernamePasswordAuthenticationFilter. Relevant sample below

<http entry-point-ref="loginUrlAuthenticationEntryPoint">
     <custom-filter  ref="rememberMeFilter" position="REMEMBER_ME_FILTER"/>
     <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"/>    
     <intercept-url pattern="/access/**" access="ROLE_USER" />
     <csrf/>
    <access-denied-handler error-page="/login" />
    <logout logout-success-url="/login?logout" />
</http>


    <beans:bean id="myWebAuthDetails"
    class="com.auth.CustomWebAuthenticationDetailsSource">
</beans:bean>

     <beans:bean id="loginFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
  <beans:property name="authenticationManager" ref="authenticationManager" />
  <beans:property name="rememberMeServices" ref="rememberMeServices" />
  <beans:property name="usernameParameter" value="username" />
  <beans:property name="passwordParameter" value="password" />
  <beans:property name="sessionAuthenticationStrategy" ref="sas" />
  <beans:property name="allowSessionCreation" value="true" />
  <beans:property name="authenticationDetailsSource" ref="myWebAuthDetails" />
  <beans:property name="authenticationFailureHandler" ref="failureHandler" />
  <beans:property name="authenticationSuccessHandler" ref="successHandler" />
  <beans:property name="filterProcessesUrl" value="/processlogin" />
</beans:bean>

回答1:


Please find the configuration below. I have mapped your xml configuration to Java config.

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated().and().formLogin()
                .authenticationDetailsSource(authenticationDetailsSource())
                .successHandler(authenticationSuccessHandler())
                .failureHandler(failureHandler()).loginPage("/login")
                .usernameParameter("usernameCustom")
                .passwordParameter("passwordCustom").permitAll().and().logout()
                .permitAll().and().rememberMe()
                .rememberMeServices(rememberMeServices());
    }

    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource() {

        return new AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails>() {

            @Override
            public WebAuthenticationDetails buildDetails(
                    HttpServletRequest request) {
                return new WebAuthenticationDetails(request);
            }

        };
    }

    @Bean
    RememberMeServices rememberMeServices() {
        RememberMeServices rememberMeServices = new RememberMeServices() {

            @Override
            public void loginSuccess(HttpServletRequest arg0,
                    HttpServletResponse arg1, Authentication arg2) {

            }

            @Override
            public void loginFail(HttpServletRequest arg0,
                    HttpServletResponse arg1) {

            }

            @Override
            public Authentication autoLogin(HttpServletRequest arg0,
                    HttpServletResponse arg1) {
                return null;
            }
        };
        return rememberMeServices;
    }

    @Bean
    AuthenticationFailureHandler failureHandler() {

        return new AuthenticationFailureHandler() {

            @Override
            public void onAuthenticationFailure(HttpServletRequest req,
                    HttpServletResponse res, AuthenticationException arg2)
                    throws IOException, ServletException {
                req.setAttribute("error", "forward");
                req.getRequestDispatcher("/homedefault").forward(req, res);
            }

        };
    }

    @Bean
    AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new AuthenticationSuccessHandler() {

            @Override
            public void onAuthenticationSuccess(HttpServletRequest req,
                    HttpServletResponse res, Authentication arg2)
                    throws IOException, ServletException {
                res.sendRedirect("homedefault");
            }
        };
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password")
                .roles("USER");
    }
}


来源:https://stackoverflow.com/questions/33360142/custom-webauthenticationdetails-programmatically-in-spring-security

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