spring security采用自定義登錄頁和退出功能


更新。。。

首先采用的是XML配置方式,請先查看  初識Spring security-添加security 在之前的示例中進行代碼修改

項目結構如下:

 

一、修改spring-security.xml文件,添加配置如下
<security:http auto-config="true">
        <security:intercept-url pattern="/admin**" access="hasRole('ROLE_USER')"/>
        <security:form-login
                login-page="/login"
                default-target-url="/welcome"
                authentication-failure-url="/login?error"
                username-parameter="user-name"
                password-parameter="pwd"/>
        <security:logout
                logout-success-url="/login?logout"/>
        <!-- XML 配置中默認csrf是關閉的,此處設置為打開
            如果這里打開csrf,則在form表單中需要添加
            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
        -->
        <security:csrf />
    </security:http>

其中:

login-page指定的用戶自定義的登錄頁面
default-target-url登錄成功以后默認跳轉到的頁面
authentication-failure-url登錄失敗以后跳轉到的頁面
username-parameter指定登錄表單中用戶名的input中name,如果這里不配置,則默認為username
password-parameter指定 登錄表單中密碼的input中name, 如果這里不配置,則默認為password
logout-success-url成功退出以后跳轉到的地址
其他見注釋
二、添加login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>login</title>
    <style>
        .error {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: #a94442;
            background-color: #f2dede;
            border: 1px solid #ebccd1;
        }
        .msg {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: #31708f;
            background-color: #d9edf7;
            border: 1px solid #bce8f1;
        }
        #login-box {
            width: 300px;
            padding: 20px;
            margin: 100px auto;
            background: #fff;
            -webkit-border-radius: 2px;
            -moz-border-radius: 2px;
            border: 1px solid #000;
        }
        .hide {
            display: none;
        }
        .show {
            display: block;
        }
    </style>
</head>
<body>
    <div id="login-box">
        <h1>Spring Security 自定義登錄頁面</h1>
        <div class="error" th:class="${error}? 'show error' : 'hide'" th:text="${error}"></div>
        <div class="msg" th:class="${msg}? 'show msg' : 'hide'" th:text="${msg}"></div>
        <form name='loginForm' action="/login" method='POST'>
            <table>
                <tr>
                    <td>用戶名:</td>
                    <td><input type='text' name='user-name' /></td>
                </tr>
                <tr>
                    <td>密碼:</td>
                    <td><input type='password' name='pwd' /></td>
                </tr>
                <tr>
                    <td colspan='2'>
                        <input type="submit" value="提交" />
                    </td>
                </tr>
            </table>
            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
        </form>
    </div>
</body>
</html>
<form name='loginForm' th:action="@{/login}" method='POST'>
<table>
<tr>
<td>用戶名:</td>
<td><input type='text' name='user-name' autofocus/></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type='password' name='pwd' /></td>
</tr>
<tr>
<td colspan='2'>
<input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
使用這個表單也可以進行登錄,提交時候自動添加_csrf屬性

 

三、修改admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>admin</title>
</head>
<body>
    <h1 th:text="|標題: ${title}|">Title : XXX</h1>
    <h1 th:text="|信息: ${message}|">Message : XXX</h1>
    <h2><a href="javascript:formSubmit()">Logout</a></h2>
    <!-- csrf for logout-->
    <form action="/logout" method="post" id="logoutForm">
        <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
    </form>
    <script>
        function formSubmit() {
            document.getElementById("logoutForm").submit();
        }
    </script>
</body>
</html>
<!-- 同樣可以進行正常退出,自動加入了_csrf的屬性值 -->
<form th:action="@{/logout}" method="post" id="logoutForm"></form>
如果使用這種表單也可以實現退出,提交時候自動添加_csrf屬性

四、修改HelloController文件,添加代碼:

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {
        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "不正確的用戶名和密碼");
        }
        if (logout != null) {
            model.addObject("msg", "你已經成功退出");
        }
        model.setViewName("login");
        return model;
    }

啟動程序:訪問http://localhost:8010/login 跳轉到自定義的登錄頁面

 


可以自行測試登錄成功和失敗的提示
 
下面采用注解方式,在前面的采用注解方式實現security和自定義登錄頁基礎之上,把配置spring-security.xml的過程改成注解方式即可
項目結構如下:
修改SecurityConfig文件
package com.petter.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;
/**
 * 相當於spring-security.xml中的配置
 * @author hongxf
 * @since 2017-03-08 9:30
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 在內存中設置三個用戶
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("hongxf").password("123456").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
    }
    /**
     * 配置權限要求
     * 采用注解方式,默認開啟csrf
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
             .and()
                .formLogin().loginPage("/login")
                .defaultSuccessUrl("/welcome").failureUrl("/login?error")
                .usernameParameter("user-name").passwordParameter("pwd")
            .and()
                .logout().logoutSuccessUrl("/login?logout")
            .and()
                .csrf();
    }
}

修改HelloController文件,添加

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {
        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "不正確的用戶名和密碼");
        }
        if (logout != null) {
            model.addObject("msg", "你已經成功退出");
        }
        model.setViewName("login");
        return model;
    }

啟動程序測試成功


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM