码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot + thymeleaf +security自定义规则 的简单使用

时间:2020-06-02 13:14:49      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:gif   属性   new   login   encode   resolve   star   memory   tco   

1.前言

以前开发一直使用 springMVC模式开发 ,前端页面常使用 JSP  ,现在html5淘汰了 ,要么使用html ,要么使用vue ,

现在使用spring boot ,有必要总结一下 spring boot 对html 的操作 。

2.环境

spring boot   2.1.6.RELEASE

3.操作

(1)下载依赖

  <!--spring security 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--访问静态资源-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

完整pom

 

技术图片
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>security-5500</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>security-5500</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--spring security 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--访问静态资源-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

 

 (2)目录结构

技术图片

 

 

  (3)resources 里的static包是存放静态资源的 ,static下面新建一个img包 ,里面放一个图片文件

启动后,直接输入网址 http://localhost:5500/img/xx.png    即可访问  ,不会被security拦截  

技术图片

 

 

 【只要pom加了security依赖包 ,将默认启动security,默认账户名 为 user 

密码是打印台打印的 随机数

技术图片

 

 

 (4)使用了thymeleaf 模板 ,那么html文件必须放在 路径为 resources/templates 的文件夹里面

否则spring boot 扫描不到文件 ,当然,也是可以修改的需要在application配置文件里修改

 技术图片

 

 

 完整的pom.xml

技术图片
spring.application.name=security-5500
# 应用服务web访问端口
server.port=5500
#配置security登录账户密和密码  ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
#spring.security.user.name=11
#spring.security.user.password=22
#
##
##
##
## Enable template caching.
#spring.thymeleaf.cache=true
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
##spring.thymeleaf.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=utf-8
## Comma-separated list of view names that should be excluded from resolution.
#spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
##设置html文件位置
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
View Code

(5)新建html文件

新建一个名为 index.html的文件 ,使用了 thymeleaf 模板的语法  th:href="@{/home}" 进行跳转  ,这个 /home路径是虚拟路径 ,需要设置的,待会展示

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
你好 ,世界 ,2333
<p>点击 <a th:href="@{/home}"></a> 去home.html页面</p>

</body>
</html>

 

 

新建一个名为 home.html的文件

 

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8">
    <title>security首页</title>
</head>
<body>
<h1>Welcome!你好,世界</h1>

<p>Click <a th:href="@{/hai}">here</a> to see a greeting.</p>
</body>
</html>

 

 

新建一个名为 hai.html的文件

 

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8">
    <title>hai文件</title>
</head>
<body>
    你好呀世界,成功登录进来了
</body>
</html>

 

 

 

新建一个名为 kk.html的文件,用于测试html文件获取静态文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>kk</title>
</head>
<body>
<img src="img/xx.png" alt="">
</body>
</html>

 

 还需要新建一个login.html文件 ,待会用来作为security的自定义登录页面

<!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自定义</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>
<br>
lalallalalal啊是德国海
</body>
</html>

 

 

 (6)设置虚拟路径用于访问html文件 【springMVC的视图设置一样,但是,不需要配置,直接引入 thymeleaf 即可使用】

在controller层

package com.example.security5500.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MVCController {

    @RequestMapping("/home")
    public String home() {
        return "home";
    }


    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/hai")
    public String hai() {
        return "hai";
    }

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("kk")
    public String kk() {
        return "kk";
    }

    //心得,index.html默认是首页,当没有指定路径 / 是哪个文件时 index.html将默认是根路径/

}

(7)测试

启动类没有改变 ,默认即可

启动程序,访问  http://localhost:5500/    将会弹出security页面

技术图片

 

 

 输入默认账户和密码 即可跳转index.html页面  

技术图片

 

 

 点击 “我” ,可跳转到home.html页面

技术图片

 

 

 

【注意 ,必须配置好了 html文件的虚拟路径

thymeleaf 模板语法

技术图片

 

 

 才可以使用,否则提示404

 好了,到了这里已经完整的解释了 spring boot 怎么使用html作为前端页面开发

(8)修改security的拦截规则

新建 文件  WebSecurityConfig 

技术图片

 

 

 源码

技术图片
package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
                .authorizeRequests()
                .antMatchers("/", "/index", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                //设置自定义登录页面
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                //设置自定义登出页面
                .logout()
//                .logoutUrl("/mylogout")
                .permitAll();
    }


}
View Code

 

再次启动工程

访问  http://localhost:5500/  可直接进入页面了 ,不需要security 验证

 技术图片

 

 

访问  http://localhost:5500/hai 会被security拦截  ,将进入配置的自定义登录页面

技术图片

 

 

 登录后才可以跳转 hai.html

 

(9)登出

登出 security 网址访问 http://localhost:5500/login?logout  ,点击蓝色大按钮即可

 技术图片

4.如何修改security的账户与密码?

(1)方法一 :

application配置文件添加属性

#配置security登录账户密和密码  ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
spring.security.user.name=11
spring.security.user.password=22

 

 完整源码

技术图片
spring.application.name=security-5500
# 应用服务web访问端口
server.port=5500
#配置security登录账户密和密码  ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
spring.security.user.name=11
spring.security.user.password=22
#
##
##
##
## Enable template caching.
#spring.thymeleaf.cache=true
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
##spring.thymeleaf.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=utf-8
## Comma-separated list of view names that should be excluded from resolution.
#spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
##设置html文件位置
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
View Code

(2)方法二:

进入刚才配置security规则的文件 WebSecurityConfig  ,直接将用户设置在内存中

 //将单个用户设置在内存中  ,在这里设置了用户信息,那么application的登录信息则不需要写
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        UserDetails user = User
                .withUsername("user")
                .password(encoder.encode("11"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

 

完整源码

技术图片
package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
                .authorizeRequests()
                .antMatchers("/", "/index", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                //设置自定义登录页面
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                //设置自定义登出页面
                .logout()
//                .logoutUrl("/mylogout")
                .permitAll();
    }


    //将单个用户设置在内存中  ,在这里设置了用户信息,那么application的登录信息则不需要写
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        UserDetails user = User
                .withUsername("user")
                .password(encoder.encode("11"))
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

}
View Code

 (3)方法三:

仍然是修改 配置security规则的文件 WebSecurityConfig

 //可以使用以下配置在内存中进行注册公开内存的身份验证{@link UserDetailsService}:
    // 在内存中添加 user 和 admin 用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication().withUser("user").password("11").roles("USER").and()
                .withUser("admin").password("11").roles("USER", "ADMIN");
    }
    // 将 UserDetailsService 显示为 Bean
    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

完整源码

技术图片
package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
                .antMatchers("/", "/index", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
                //设置自定义登录页面
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                //设置自定义登出页面
                .logout()
//                .logoutUrl("/mylogout")
                .permitAll();

    }
    

    //可以使用以下配置在内存中进行注册公开内存的身份验证{@link UserDetailsService}:
    // 在内存中添加 user 和 admin 用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication().withUser("user").password("11").roles("USER").and()
                .withUser("admin").password("11").roles("USER", "ADMIN");
    }
    // 将 UserDetailsService 显示为 Bean
    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}
View Code

 

 

 

【注意: 三个方法任选一个都可以修改登录账号密码,但是,方法2和3不能同时使用 ,如果WebSecurityConfig 和application 文件 都写上 ,会导致application配置文件设置的账号密码失效,仅WebSecurityConfig内的方法设置的有效】

 

spring boot + thymeleaf +security自定义规则 的简单使用

标签:gif   属性   new   login   encode   resolve   star   memory   tco   

原文地址:https://www.cnblogs.com/c2g5201314/p/13030335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!