我是这样使用SpringBoot(自定义登录界面)

目录

Spring Security自带的登录界面比较简单,不能完成多变的需求,这章来完成自定义登录界面。

修改配置

在configure(HttpSecurity http)中,.formLogin().loginPage加入自定义界面的URI,使Spring Security跳转到自己定义的一个地址。代码:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/home").permitAll() // 这三个目录不做安全控制
                    .anyRequest().authenticated()
                    .and()
                .formLogin().loginPage("/login").permitAll(); // 自定义的登录页面
    }

写界面

路径配置好了,需要把“/login”实现。在“com.biboheart.demos.security”中创建一个controller包(把安全控制相关的都加到在com.biboheart.demos.security包下进行)。在com.biboheart.demos.security.controller下创建Class,名称为SecurityController。完成“login”页面导航。

package com.biboheart.demos.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SecurityController {

    @RequestMapping(value = "/login", method = {RequestMethod.GET})
    public String getAccessConfirmation() {
        return "login";
    }

}

在templates下创建login.html




    Spring Security Example


    

启动项目,访问http://localhost

首页

点击连接“这里”跳转hello页面,却跳转到了自己写的登录界面。是不是与上一章节《Spring Security实现用户登录》不同了。
自定义的登录界面

貌似比它自带的要丑,这个可以用CSS随意处理了。
输入用户名:user,密码:123,点击登录。进入hello页面。
hello界面

退出登录

前面没做退出功能,界面有了登录还要有退出,这样才完整。
先在Hello界面中加个跳转到首页的。

// hello.html



    Hello World!


    

点击 这里 返回首页.

Hello

结果如下,点击“这里”后可以加到首页


加了返回首页

在界面中加入下面代码就可以实现登出。

    
点击

界面效果,点击“登出”即可退出登录,默认跳转到/login页面。


登出按钮

这里有个问题,不论有没有登录都会显示登出按钮。如果在需要登录的页面还好,在首页登出的话就需要判断一下当前是否有用户登录中,有的话才显示。Spring Security 提供了 thymeleaf 标签,需要在pom.xml中引入。

        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity5
        

修改页面中登出按钮

    
登录者:
点击

配置登出后页面

如果登出后想要返回到首页,可以改配置文件登出后跳转的URL。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/home").permitAll() // 这三个目录不做安全控制
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")// 自定义的登录页面
                    .permitAll()
                    .and()
                .logout()
                    .logoutSuccessUrl("/");
    }

你可能感兴趣的:(我是这样使用SpringBoot(自定义登录界面))