Spring Security 登录时如何获取其他参数(可用作校验验证码)

情景:在使用Security时,在校验用户名,也就是在自定义的UserDetailsService类中loadUserByUsername方法只传入一个用户名参数,但需求往往可能携带多个参数校验,如何获取另外的参数,可以增加自定义的Security过滤器链来获取表单的其他参数或者校验验证码,并把自定义的过滤器链设置在security的UsernamePasswordAuthenticationFilter过滤器之前。

图解:在这里插入图片描述

环境: IDEA版本2017.3.1 x64, JDK1.8, SpringBoot2.1.1, Druid1.1.8, mybatis1.3.2,Security5.1.2,thymeleaf3.0.11

总流程:

  • 增加自定义的Security过滤器链,用来获取表单其他参数或者校验验证码
  • 在项目中的SecurityConfig配置类中配置自定义的过滤器链在security验证用户之前

一、增加自定义的Security过滤器链,用来获取表单其他参数

  • 此过滤器链是用来获取表单上的学校id参数
public class SchoolAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    //拦截的url
    private String processUrl;

    public SchoolAuthenticationFilter(String defaultFilterProcessesUrl, String failureUrl) {
        super(defaultFilterProcessesUrl);
        this.processUrl = defaultFilterProcessesUrl;
        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse)response;
        if(processUrl.equals(req.getServletPath()) && "POST".equalsIgnoreCase(req.getMethod())){
            //获取表单的学校id参数
            Integer schoolId = Integer.valueOf(req.getParameter("schoolId"));
            //将学校id存入session
            req.getSession().setAttribute("school",schoolId);
        }
        chain.doFilter(request, response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException, ServletException {
        return null;
    }
}

由以上代码可以知道,已经获取了表单的学校id参数,同理,也可以在此过滤器做其他业务判断,例如校验验证码

二、在项目中的SecurityConfig配置类中配置自定义的过滤器链在security验证用户之前

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用csrf防御机制(跨域请求伪造),这么做在测试和开发会比较方便。
        http.csrf().disable();

		//配置自定义过滤器在security的UsernamePasswordAuthenticationFilter过滤器之前
        http.addFilterBefore(new SchoolAuthenticationFilter("/login", "/login?error"), UsernamePasswordAuthenticationFilter.class);

        //开启记住我功能
        http.rememberMe();
    }

参考来源:https://blog.csdn.net/dushiwodecuo/article/details/78913113

发布了151 篇原创文章 · 获赞 126 · 访问量 37万+
展开阅读全文

Spring Security 无法进入UserServiceDetails方法

03-24

项目启动不报错,直接在浏览器中输入/spitter/home也会直接跳转到spitter/login页面,但是一但提交表单,会直接进入到后台login方法,而不会进入到UserDetailsService方法中,而且也不会按照方法正常执行的那样跳转到home页面,而是返回到了login页面,求解。。。。。 ``` package cherry.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; // 配置DelegatingFilterProxy public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{ } ``` ``` package cherry.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService spitterUserDetailsService; @Override protected void configure(HttpSecurity http) throws Exception{ http.formLogin().loginPage("/spitter/login").permitAll() .and().rememberMe() .and().authorizeRequests().antMatchers("/spitter/home").hasRole("SPITTER") .anyRequest().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception{ auth.userDetailsService(spitterUserDetailsService); } } ``` ``` package cherry.config.security; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import cherry.model.Spitter; import cherry.repository.SpitterRepository; @Service public class SpitterUserDetailsService implements UserDetailsService { @Autowired private SpitterRepository spitterRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { System.err.println("---------- User Details Service start -----------"); Spitter spitter = spitterRepository.findByUsername(username); if(spitter == null){ throw new UsernameNotFoundException(username + " not found "); } List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_SPITTER")); System.out.println(spitter.getUsername() + " : ROLE_SPITTER"); return new User(spitter.getUsername(), spitter.getPassword(), authorities); } } ``` ``` package cherry.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cherry.model.Spitter; import cherry.repository.SpitterRepository; @Controller @RequestMapping("/spitter") public class SpitterController { @Autowired private SpitterRepository spitterRepository; @RequestMapping(value= "/login", method = RequestMethod.GET) public String login(Model model){ model.addAttribute("spitter", new Spitter()); return "spitter/login"; } @RequestMapping(value= "/loginForm", method = RequestMethod.POST) public String login(@ModelAttribute("spitter") Spitter spitter){ System.out.println(spitter.getUsername() + " logined.."); return "redirect:home"; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String showRegistrationForm(Model model){ model.addAttribute("spitter", new Spitter()); return "spitter/registerForm"; } @RequestMapping(value="/register", method = RequestMethod.POST) public String register(@ModelAttribute("spitter") Spitter spitter){ spitterRepository.addSpitter(spitter); return "spitter/registerSuccessfully"; } @RequestMapping("/home") public String hello(){ return "spitter/helloWorld"; } } ``` 附:https://github.com/CherryYu/SpringHibernate.git 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 程序猿惹谁了 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览