學習spring security(一 ) demo

1.跟着spring官方給的guide作個demo,來學習spring security.html

首先引入依賴:java

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.cloud:spring-cloud-starter-security')
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

2.配置springmvc web

package com.test.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {


    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

3.配置spring securityspring

package com.test.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }


    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

以上配置作了以下工做安全

  • 除了「/」,」/home」(首頁),」/login」(登陸),」/logout」(註銷),以外,其餘路徑都須要認證,以上4個path是容許全部人全部角色訪問。
  • 指定「/login」該路徑爲登陸頁面,當未認證的用戶嘗試訪問任何受保護的資源時,都會跳轉到「/login」,好比若是用戶訪問下面的hello頁面時,也會跳轉到/login.
  • 默認指定「/logout」爲註銷頁面
  • 配置一個內存中的用戶認證器,使用user/password做爲用戶名和密碼,具備USER角色

4.項目的啓動點mvc

package com.test.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class application {


    public static void main(String[] args) {
        SpringApplication.run(application.class, args);

    }
}

5.接下來是要訪問的頁面,其中home.html,login.html是不受安全控制的頁面;app

而hello.html頁面是受安全控制的。ide

home.html  主要是歡迎頁面,並有個跳轉連接到hello頁面,可是hello頁面須要安全驗證spring-boot

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>

hello.htmlpost

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
    Invalid username and password.
</div>
<div th:if="${param.logout}">
    You have been logged out.
</div>
<form th:action="@{/login}" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

 

運行後運行結果以下:

登陸http://localhost:8080/ 跳轉到home頁面

而後點擊here要去往hello頁面,點擊here後跳轉到如下要輸入用戶名和密碼的頁面,由於要訪問hello頁面是須要權限的。

此時輸入一個錯誤的用戶名和密碼,

點擊登陸,會爆出錯誤的信息以下:

若是輸入正確的,用戶名和密碼,以上在SecurityConfiguration類中設置的user password,會出現如下頁面:

而後點擊sign out

相關文章
相關標籤/搜索