使用spring secuity自定义登录

我们先看spring secuity的默认登录页面,

  • 加入springmvc,spring secuityservlet的一些依赖,配置jetty的插件,配置端口是8001,contextPath是"/"
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


    <build>
        <finalName>secuity-quickstart-config</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.3.v20170317</version>
                <configuration>
                    <httpConnector>
                        <port>8001</port>
                    </httpConnector>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • 定义系统启动类
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //系统启动的时候的根类
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebAppConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    //设置成/*表示拦截静态的文件
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}
  • web入口类
/**
 *
 * 入口类,启动spring mvc,启动spring secuity
 */
@EnableWebMvc
@EnableWebSecurity
@ComponentScan("com.zhihao.miao.secuity")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}
  • spring security配置类
/**
 *
 * 初始化spring security
 */
public class WebAppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    protected String getDispatcherWebApplicationContextSuffix() {
        return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
    }
}
  • 具体的controller
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello spring secuity";
    }

    @GetMapping("/home")
    public String home(){
        return "home spring security";
    }

    @GetMapping("/admin")
    public String admin(){
        return "admin spring secuity";
    }
}
  • 权限用户名密码的具体配置
Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");


        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        //httpbasee认证
        http.httpBasic();
    }
}
  • 默认的登录页面


    httpbasic认证

http.formLogin();是spring secuity默认的登录页面。

自定义登录

  • 先定义一个登录页面,将其页面放在了WEB-INF下面的jsp目录下,然后需要在启动类上加入视图解析器
@EnableWebMvc
@EnableWebSecurity
@ComponentScan("com.zhihao.miao.secuity")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

     //配置视图解析器
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp();
    }
}
  • Controller中定义一个url跳转到该登录页面

根据上面的视图解析器,我们就知道登录的跳转页面的路径是/WEB-INF/jsp/login.jsp

@Controller
public class LoginController {

    @GetMapping("/sys/login")
    public String login(){
        return "/jsp/login";
    }
}
  • spring security中配置

登录的跳转页面,和登录的动作url不去做权限认证。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登录的跳转页面,和登录的动作url不应该有权限认证。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                //登录的时候跳转的登录页面url
                loginPage("/sys/login").
               //登录页面提交时候的请求
                loginProcessingUrl("/doLogin").
                defaultSuccessUrl("/public/login/ok.html"). //如果直接访问登录页面,则登录成功后重定向到这个页面,否则跳转到之前想要访问的页面
                permitAll(); //就是设置loginProcessingUrl()也不需要权限认证
    }
}
  • 登录页面:

详细的登录页面可以查看文章的最后的项目链接

<div class="login">
    <h1>Login</h1>
    <form method="post" action="/doLogin">
        <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
        <input type="text" name="username" placeholder="用户名" />
        <input type="password" name="password" placeholder="密码"/>
        <button type="submit" class="btn btn-primary btn-block btn-large">登录</button>
    </form>
</div>
  • 测试
    访问localhost:8001/hello,跳转到http://localhost:8001/sys/login页面,具体页面如下:
  • 一些更加细节的定制登录的api使用

比如说失败重定向(可以在重定向方法中获取到失败的异常),失败跳转,成功登录之后重定向等等api的使用

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //账号被锁
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").accountLocked(true).roles("GUEST");
        //账号过期
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").accountExpired(true).roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登录的跳转页面,和登录的动作url不应该有权限认证。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                failureForwardUrl("/sys/loginFail").   //使用forward的方式,能拿到具体失败的原因,并且会将错误信息以SPRING_SECURITY_LAST_EXCEPTION的key的形式将AuthenticationException对象保存到request域中
                        //failureUrl("/public/login/fail.html").   //失败重定向,拿不到具体失败的原因
                defaultSuccessUrl("/public/login/ok.html"). //如果直接访问登录页面,则登录成功后重定向到这个页面,否则跳转到之前想要访问的页面
                //defaultSuccessUrl("/public/login/ok.html",true). //登录成功后,都直接重定向到这个页面
                        permitAll();
    }
}

比如说重定向拿不到登录失败的异常,而failureForwardUrl()的api却可以,点入failureForwardUrl源码查看,FormLoginConfigurer的文档说明,如果登录失败会抛出
SPRING_SECURITY_LAST_EXCEPTION异常,取到消息可以使用${SPRING_SECURITY_LAST_EXCEPTION.message}

可以在Controller层中通过HttpServletRequest拿到登录失败的异常,

    @PostMapping("/sys/loginFail")
    public String fail(HttpServletRequest req){
        AuthenticationException exp = (AuthenticationException)req.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        System.out.println("exp:"+exp.getMessage());
        if(exp instanceof BadCredentialsException){
            //将错误信息放到request域中
            req.setAttribute("error_msg", "用户名或密码错误");
        } else if(exp instanceof AccountExpiredException){
            req.setAttribute("error_msg", "账户过期");
        } else if(exp instanceof LockedException){
            req.setAttribute("error_msg", "账户已被锁");
        }else{
            //其他错误打印这些信息
            System.out.println(exp.getMessage());
        }
        return "/jsp/login";
    }

登录页面打印失败的异常

<div class="login">
    <h1>Login</h1>
    <form method="post" action="/doLogin">
        <input type="hidden" name="${ _csrf.parameterName}" value="${ _csrf.token}" />
        <input type="text" name="username" placeholder="用户名" />
        <input type="password" name="password" placeholder="密码"/>
        <button type="submit" class="btn btn-primary btn-block btn-large">登录</button>
    </form>
    <div class="login-bottom" style="color:red;">${SPRING_SECURITY_LAST_EXCEPTION.message}</div>
</div>

此时就可以把错误信息打印到页面上

  • 还可以自定义登录成功和失败的handler进行权限验证,自己根据自己的业务代码来进行定制
    通过successHandlerfailureHandler方法来定义
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("GUEST");
        auth.inMemoryAuthentication().withUser("zhihao.miao").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("lisi").password("12345678").roles("USER", "ADMIN");
    }

    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/hello").hasRole("GUEST");
        http.authorizeRequests().antMatchers("/home").hasRole("USER");
        http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN");

        //登录的跳转页面,和登录的动作url不应该有权限认证。
        http.authorizeRequests().antMatchers("/sys/login").permitAll();
        http.authorizeRequests().antMatchers("/**/*.html").permitAll();
        http.authorizeRequests().antMatchers("/**/*.css").permitAll();
        http.authorizeRequests().antMatchers("/**/*.js").permitAll();
        http.authorizeRequests().antMatchers("/**/*.png").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        http.formLogin().
                loginPage("/sys/login").
                loginProcessingUrl("/doLogin").
                successHandler((request, response, authentication) -> {
                    //登录成功的时候跳转到/public/login/ok.html
                    System.out.println("========登陆成功=======" + authentication.getName());
                    response.sendRedirect("/public/login/ok.html");
                }).failureHandler((request, response, exception) -> {
                    //登录失败的时候跳转到/public/login/fail.html
                    System.out.println("=======登陆失败=======" + exception.getMessage());
                    response.sendRedirect("/public/login/fail.html");
                }).permitAll();
    }
}

参考代码

secuity-config-login

参考资料

官方文档
Spring Security 从入门到进阶系列教程

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,780评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,424评论 1 305
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,397评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,576评论 0 218
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,997评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,945评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,107评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,850评论 0 208
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,625评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,804评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,285评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,613评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,291评论 3 242
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,164评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,963评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,096评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,886评论 2 278

推荐阅读更多精彩内容