百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

分布式系统开发实战:基于Spring Security实现安全认证

yuyutoo 2024-10-26 16:08 3 浏览 0 评论

在本节,将演示基于Spring Security安全认证功能。该应用代码可以在security basic目录下找到。

19.5.1 添加依赖

添加Spring Security的依赖时,由于是使用的snapshot版本,所以,要配置Spring Snapshots仓库。配置如下。

<!-- Spring Snapshots仓库 -->
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
</repositories>
<properties>
<spring.version>5.1.5.RELEASE</spring.version>
<jetty.version>9.4.14.v20181114</jetty.version>
<jackson.version>2.9.7</jackson.version>
<spring-security.version>5.2.0.BUILD-SNAPSHOT</spring-security.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency><!-- 安全相关的依赖 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
</dependencies>

19.5.2 添加业务代码

业务代码里面包含了模型和控制器。

1.User模型

User类代码如下。

package com.waylau.spring.mvc.vo;
public class User {
private String username;
private Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
//省略getter/setter方法
}

2.控制器

控制器HelloController代码如下。

package com.waylau.spring.mvc.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.waylau.spring.mvc.vo.User;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "Hello World! Welcome to visit waylau.com!";}
@RequestMapping("/hello/way")
public User helloWay() {
return new User("Way Lau", 30);
}
}

上述控制器的逻辑非常简单,当访问“/hello”时,会响应一段文本;当访问“/hello/way”会返回一个POJO对象。

该POJO对象,可以根据消息转换器的设置,来生成不同格式的消息。

19.5.3 配置消息转换器

添加Spring Web MVC的配置类MvcConfiguration,并在该配置中启用消息转换器。

package com.waylau.spring.mvc.configuration;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc // 启用MVC
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
public void extendMessageConverters(List<HttpMessageConverter<?>> cs) {
// 使用Jackson JSON来进行消息转换
cs.add(new MappingJackson2HttpMessageConverter());
}
}

由于预先在pom.xml中添加了Jackson JSON的依赖,因此可以使用

Jackson JSON来进行消息转换,将响应消息体转为JSON格式。

19.5.4 配置Spring Security

以下是针对Spring Security的配置。

package com.waylau.spring.mvc.configuration;
import org.springframework.context.annotation.Bean;
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.WebSecurityConfigurerAd
apter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@EnableWebSecurity // 启用Spring Security功能
public class WebSecurityConfig
extends WebSecurityConfigurerAdapter {
/**
* 自定义配置
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()//所有请求都需认证
.and()
.formLogin() // 使用form表单登录
.and()
.httpBasic(); // HTTP基本认证
}
@SuppressWarnings("deprecation")
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager =
new InMemoryUserDetailsManager();
manager.createUser(
User.withDefaultPasswordEncoder() // 密码编码器
.username("waylau") // 用户名
.password("123") // 密码
.roles("USER") // 角色
.build()
);
return manager;
}
}

在上述配置中,要启动Spring Security功能,需要在配置类上添加@EnableWebSecurity注解。

安全配置类WebSecurityConfig继承自

WebSecurityConfigurerAdapter。WebSecurity Configurer Adapter提供用于创建一个Websecurityconfigurer实例方便的基类,允许自定义重写其方法。这里,我们重写了configure方法:authorizeRequests().anyRequest().authenticated()方法意味着所有请求都需认证;formLogin()方法表明这是基于表单的身份验证;httpBasic()方法表明该认证是一个HTTP基本认证。

UserDetailsService用于提供身份认证信息。本例使用了基于内存的信息管理器InMemory UserDetailsManager,同时初始化了一个用户名为“waylau”、密码为“123”、角色为“USER”的身份信息。withDefaultPasswordEncoder()方法指定了该用户身份信息使用默认的密码编码器。

19.5.5 创建应用配置类

AppConfiguration是整个应用的配置类,用于导入Spring Web MVC及Spring Security的配置信息。代码如下。

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan(basePackages = { "com.waylau.spring" })
@Import({ WebSecurityConfig.class, MvcConfiguration.class})
public class AppConfiguration {
}

19.5.6 创建内嵌Jetty的服务器

创建内嵌了Jetty的服务器,代码如下。

package com.waylau.spring.mvc;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;
import com.waylau.spring.mvc.configuration.AppConfiguration;
public class JettyServer {
private static final int DEFAULT_PORT = 8080;
private static final String CONTEXT_PATH = "/";
private static final String MAPPING_URL = "/*";
public void run() throws Exception {
Server server = new Server(DEFAULT_PORT);
server.setHandler(servletContextHandler(webApplicationContext()));
server.start();
server.join();
}
private ServletContextHandler servletContextHandler(WebApplicationContext ct) {
// 启用Session管理器
ServletContextHandler handler =
new ServletContextHandler(ServletContextHandler.SESSIONS);
handler.setContextPath(CONTEXT_PATH);
handler.addServlet(new ServletHolder(new DispatcherServlet(ct)),
MAPPING_URL);
handler.addEventListener(new ContextLoaderListener(ct));
// 添加Spring Security过滤器
FilterHolder filterHolder=new FilterHolder(DelegatingFilterProxy.class);
filterHolder.setName("springSecurityFilterChain");
handler.addFilter(filterHolder, MAPPING_URL,
EnumSet.of(DispatcherType.REQUEST));
return handler;
}
private WebApplicationContext webApplicationContext() {
AnnotationConfigWebApplicationContext context =
new AnnotationConfigWebApplicationContext();
context.register(AppConfiguration.class);
return context;
}
}

JettyServer将Spring的上下文Servlet、监听器、过滤器等信息都传给了Jetty服务。

19.5.7 应用启动器

创建应用启动类Application,代码如下。

package com.waylau.spring.mvc;
public class Application {
public static void main(String[] args) throws Exception {
new JettyServer().run();
}
}

19.5.8 运行应用

右键运行Application类即可启动应用。

访问http://localhost:8080/hello/way,会跳转到登录界面,意味着被安全认证拦截了。正如WebSecurityConfig所配置的那样,登录界面是一个form表单,

尝试输入一个错误的用户名和密码,可以看到所示的错误提示信息。


用初始化好的用户名和密码进行成功登录,可以看到能够正常访问应用的API

19.6 本章小结

本章介绍了分布式系统安全性的基本概念、加密算法,同时也介绍了安全通道及访问控制。本章也演示了如何基于Spring Security框架来实现安全认证。

相关推荐

如何在HTML中使用JavaScript:从基础到高级的全面指南!

“这里是云端源想IT,帮你...

推荐9个Github上热门的CSS开源框架

大家好,我是Echa。...

前端基础知识之“CSS是什么?”_前端css js

...

硬核!知网首篇被引过万的论文讲了啥?作者什么来头?

整理|袁小华近日,知网首篇被引量破万的中文论文及其作者备受关注。知网中心网站数据显示,截至2021年7月23日,由华南师范大学教授温忠麟等人发表在《心理学报》2004年05期上的学术论文“中介效应检验...

为什么我推荐使用JSX开发Vue3_为什么用vue不用jquery

在很长的一段时间中,Vue官方都以简单上手作为其推广的重点。这确实给Vue带来了非常大的用户量,尤其是最追求需求开发效率,往往不那么在意工程代码质量的国内中小企业中,Vue占据的份额极速增长...

【干货】一文详解html和css,前端开发需要哪些技术?
【干货】一文详解html和css,前端开发需要哪些技术?

网站开发简介...

2025-02-20 18:34 yuyutoo

分享几个css实用技巧_cssli

本篇将介绍几个css小技巧,目录如下:自定义引用标签的符号重置所有标签样式...

如何在浏览器中运行 .NET_怎么用浏览器运行代码

概述:...

前端-干货分享:更牛逼的CSS管理方法-层(CSS Layers)

使用CSS最困难的部分之一是处理CSS的权重值,它可以决定到底哪条规则会最终被应用,尤其是如果你想在Bootstrap这样的框架中覆盖其已有样式,更加显得麻烦。不过随着CSS层的引入,这一...

HTML 基础标签库_html标签基本结构
HTML 基础标签库_html标签基本结构

HTML标题HTML标题(Heading)是通过-...

2025-02-20 18:34 yuyutoo

前端css面试20道常见考题_高级前端css面试题

1.请解释一下CSS3的flexbox(弹性盒布局模型),以及适用场景?display:flex;在父元素设置,子元素受弹性盒影响,默认排成一行,如果超出一行,按比例压缩flex:1;子元素设置...

vue引入外部js文件并使用_vue3 引入外部js

要在Vue中引入外部的JavaScript文件,可以使用以下几种方法:1.使用``标签引入外部的JavaScript文件。在Vue的HTML模板中,可以直接使用``标签来引入外部的JavaScrip...

网页设计得懂css的规范_html+css网页设计

在初级的前端工作人员,刚入职的时候,可能在学习前端技术,写代码不是否那么的规范,而在工作中,命名的规范的尤为重要,它直接与你的代码质量挂钩。网上也受很多,但比较杂乱,在加上每年的命名都会发生一变化。...

Google在Chrome中引入HTML 5.1标记

虽然负责制定Web标准的WorldWideWebConsortium(W3C)尚未宣布HTML5正式推荐规格,而Google已经迁移到了HTML5.1。即将发布的Chrome38将引入H...

HTML DOM 引用( ) 对象_html中如何引用js

引用对象引用对象定义了一个同内联元素的HTML引用。标签定义短的引用。元素经常在引用的内容周围添加引号。HTML文档中的每一个标签,都会创建一个引用对象。...

取消回复欢迎 发表评论: