惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
S
SegmentFault 最新的问题
Jina AI
Jina AI
D
DataBreaches.Net
人人都是产品经理
人人都是产品经理
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
B
Blog
博客园 - 【当耐特】
博客园 - Franky
M
MIT News - Artificial intelligence
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
Last Week in AI
Last Week in AI
Engineering at Meta
Engineering at Meta

回忆中的明天

自己写一个Web 端的MiMo TTS Chat,方便实现文本转语音,API限免中 · 回忆中的明天 NVIDIA NIM 开发平台,提供超多免费大模型 · 回忆中的明天 iTranslation 简单快捷的翻译软件,支持数十种语言互译 · 回忆中的明天 国内外免费大模型平台,支持 API 调用的超多免费大模型 · 回忆中的明天 SiliconFlow 硅基流动一站式大模型云服务平台,提供超多免费大模型 · 回忆中的明天 Xiaomi MiMo 小米大模型团队开发的大语言模型,开源限免中…… · 回忆中的明天 BigModel 智谱大模型开放平台,提供超多自研免费大模型 · 回忆中的明天 OpenRouter 模型聚合平台,提供超多免费模型使用 · 回忆中的明天 iReader 英语点读学习系统,译林小学英语在线点读 · 回忆中的明天 ZenMux 企业级大模型聚合平台,提供免费试用模型 Gemini 3 Pro · 回忆中的明天 英语学习,新概念英语在线点读、全文朗读学习系统 · 回忆中的明天 iGSTT(Gemini STT) 开源免费的语音转文本(STT)的命令行工具 · 回忆中的明天 Python 项目打包,并上传到 PyPI,分享项目 · 回忆中的明天 iGTTS(Gemini TTS) 开源免费的文本转语音(TTS)的命令行工具 · 回忆中的明天 iChat(AI Chat) 智能聊天工具,支持 MiMo、DeepSeek、Gemini、Grok、OpenAI和自定义AI · 回忆中的明天 NanoPi R2S 安装 Debian 固件系统,旁路由网络代理内网转发,决解直连网络卡顿 nftables · 回忆中的明天 NanoPi R2S Armbian Linux 旁路由网络代理内网转发,决解直连网络卡顿 iptables · 回忆中的明天 sing-box rule-set · 回忆中的明天 Xcode 最全最实用的快捷键列表 · 回忆中的明天 SwiftUI 中的@State、@Bindable和@Binding · 回忆中的明天 免费的图床服务器-GitHub Pages · 回忆中的明天 A Free Native Image Uploading Tool for macOS · 回忆中的明天 免费的图床服务器-Cloudflare-R2 · 回忆中的明天 图传 (iUploader) - macOS 免费原生图床上传利器 · 回忆中的明天 本地无法加载托管到Cloudflare中的图片等资源,权限错误403 · 回忆中的明天 国内、外免费公共的DNS,支持的DoH,防止污染、篡改的问题 · 回忆中的明天 macOS 系统下载和安装 · 回忆中的明天 使用 CURL 命令调试和诊断网络问题,网站请求测速 · 回忆中的明天 WARP Beta for macOS 支持新协议 MASQUE · 回忆中的明天 2024年自用国外靠谱的 VPS 服务器推荐 · 回忆中的明天
Spring Security 快速创建登录权限,安全管理资源权限 · 回忆...
2021-11-20 · via 回忆中的明天

原文:https://ichochy.com/posts/spring/20211120.html


使用 Spring Security 合理配置页面权限,管理用户登录权限,实现页面安全

开发工具

  • IDEA: 2021.1.2
  • Java: 1.8
  • Spring Boot: 2.5.2

创建项目

打开 IDEA 创建新项目 New Project,使用 start.spring.io 快速构建 16226365527086133

添加 Spring Web 依赖,finish 创建项目 16226367387048384

pom.xml 添加依赖

添加 Spring Security 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

编写项目

创建登录页面

templates/login.html

<!--
  ~ Copyright (c) 2021 iChochy
  ~ URL:https://ichochy.com
  ~ Date:2021/06/10 19:44:10
  -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>

<h1>Login</h1>

<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>

创建form表单,登录地址/login,方法为post

创建登出按钮

templates/index.html

<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="Sign Out"/>
</form>

httpServletRequest.remoteUser获取当前登录用户

登出地址/logout,方法为post

配置 MvcConfig

创建com/ichochy/example/MvcConfig.java

/*
 * Copyright (c) 2021 iChochy
 * URL:https://ichochy.com
 * Date:2021/11/22 19:24:22
 */

package com.ichochy.example;

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("/login").setViewName("login");
    }
}

添加登录页面控制器,指定地址/login

登录安全权限配置

创建 WebSecurityConfig,继承 WebSecurityConfigurerAdapter

/*
 * Copyright (c) 2021 iChochy
 * URL:https://ichochy.com
 * Date:2021/11/22 20:06:22
 */

package com.ichochy.example.login;

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.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login").permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService(){
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        UserDetails userDetails = User.builder()
                .passwordEncoder(encoder::encode)
                .username("MLeo")
                .password("iChochy")
                .roles("iChochy")
                .build();
        return new InMemoryUserDetailsManager(userDetails);
    }
}

重写configure,配置登录权限,配置非认证(permitAll)地址和认证(authenticated)地址,loginPage自定义登录页面和权限,logout自定义登出页面和权限

userDetailsService方法设置用户登录信息存入内存,校验用户登录信息

  • passwordEncoder指定密码加密编码
  • username指定用户为:MLeo
  • password指定密码为:iChochy
  • roles指定角色为:iChochy

项目目录

├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── ichochy
        │           └── example
        │               ├── ExampleApplication.java
        │               ├── MvcConfig.java
        │               └── login
        │                   └── WebSecurityConfig.java.java
        └── resources
            ├── application.properties
            ├── static
            └── templates
                ├── index.html
                └── login.html

运行项目

启动器 ExampleApplication

/*
 * Copyright (c) 2021 iChochy
 * URL:https://ichochy.com
 * Date:2021/06/09 22:07:09
 */

package com.ichochy.example;

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

@SpringBootApplication
public class ExampleApplication {

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

Dubug 运行项目,启动成功后可以看到默认端口号为8080 16226399326197735

浏览器访问 http://localhost:8080,自动302重定向到登录页面 16378405780119936

登录成功页面 16378406340097327

总结

使用 Spring Security 管理登录权限,实现项目权限安全

GitHub

https://github.com/iChochy/Example

引用