当前位置: 首页 > news >正文

瑞安 网站建设浙江省建设信息港三类人员证书查询

瑞安 网站建设,浙江省建设信息港三类人员证书查询,手机系统网站有哪些,4.1进行网站建设与推广应用Spring Security 前面介绍了在项目开发时为什么选择Spring Security#xff0c;还介绍了它的原理。本节开始动手实践Spring Security的相关技术。 实战#xff1a;Spring Security入门 现在开始搭建一个新项目#xff0c;实践一个Spring Security的入门程序。 …应用Spring Security 前面介绍了在项目开发时为什么选择Spring Security还介绍了它的原理。本节开始动手实践Spring Security的相关技术。 实战Spring Security入门 现在开始搭建一个新项目实践一个Spring Security的入门程序。 1新建一个spring-security-demo模块添加项目依赖在pom.xml中添加如下依赖 properties java.version11/java.version /properties dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-security/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-thymeleaf/artifactId /dependency !--thymeleaf对security5的支持依赖-- dependency groupIdorg.thymeleaf.extras/groupId artifactIdthymeleaf-extras-springsecurity5/artifactId !--version3.0.4.RELEASE/version-- /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency dependency groupIdjavax.servlet/groupId artifactIdjavax.servlet-api/artifactId version4.0.1/version /dependency /dependencies build plugins plugin groupIdorg.springframework.boot/groupId artifactIdspring-boot-maven-plugin/artifactId /plugin /plugins /build 2在application.properties中添加Spring Security配置配置当前登录的用户名和密码配置内容如下 #登录的用户名 spring.security.user.nameadmin #登录的密码 spring.security.user.password123456 3在resources文件夹下创建页面add.html表示添加页面代码如下 !DOCTYPE html html xmlns:thhttps://www.thymeleaf.org head title/title /head body add 页面 /body /html 4添加主页home.html代码如下 !DOCTYPE html html xmlns:thhttps://www.thymeleaf.org head title主页/title /head body 你已经登录成功 form th:action{/logout} action/login methodpost input typesubmit value退出系统/ /form /body /html 5添加login.html登录页用于用户的登录代码如下 !DOCTYPE html html xmlns:thhttps://www.thymeleaf.org head title请登录/title /head body div form th:action{/login} methodpost action/login p span请输入用户名:/span input typetext idusername nameusername /p p span请输入密码:/span input typepassword idpassword namepassword /p input typesubmit value登录/ /form /div /body /html 6在resources文件夹下创建一个css文件夹新建一个my.css文件内容如下 my css file 7新建一个Controller包再新建如下3个Controller。 AddController类用于返回add页面代码如下 package com.example.springsecuritydemo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; Controller public class AddController { GetMapping(/add) public String ad(){ return add; } } omeController类用于访问home页面代码如下 package com.example.springsecuritydemo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; Controller public class HomeController { GetMapping(/home) public String home(){ return home; } } LoginController类用于用户登录代码如下 package com.example.springsecuritydemo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; Controller public class LoginController { GetMapping(/login) public String login(){ return login; } } 8新建一个config包添加Spring Security配置文件 WebSecurityConfig package com.example.springsecuritydemo.config; import com.example.springsecuritydemo.service.LoginSuccessHandler; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecuri ty; import org.springframework.security.config.annotation.web.configuration.WebSe curityConfigurerAdapter; Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { Override protected void configure(HttpSecurity http) throws Exception { // 关闭csrf校验 http.csrf().disable(); // 配置登录页面用户名和密码已在配置文件中 http.formLogin().loginPage(/login).permitAll(); // 配置登录成功后的操作 http.formLogin().successHandler(new LoginSuccessHandler()); // 登录授权 http.logout().permitAll(); // 授权配置 http.authorizeRequests() /* 所有的静态文件可以访问 */ .antMatchers(/js/**,/css/**,/images/**).permitAll() /* 所有的以/add 开头的 add页面可以访问 */ .antMatchers(/add/**).permitAll() .anyRequest().fullyAuthenticated(); } } 9新建一个登录成功后的业务处理服务类LoginSuccessHandler代码如下 package com.example.springsecuritydemo.service; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.Authentication SuccessHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 登录成功后的业务处理类 */ public class LoginSuccessHandler implements AuthenticationSuccessHandler { Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { System.out.println(登录成功); //重定向到home.html页面 response.sendRedirect(/home); } } 10添加当前项目的启动类 SpringSecurityDemoApplication使用注解EnableWeb- Security启动Spring Security功能 package com.example.springsecuritydemo; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; EnableWebSecurity SpringBootApplication public class SpringSecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringSecurityDemoApplication.class, args); } } 11执行 SpringSecurityDemoApplication启动当前项目访问localhost:8080因为没有登录所以跳转到登录页如图5.1所示。再访问localhost:8080/home还是会自动跳转到登录页面因为没有登录。前两次访问Spring Security时会自动判断用户还未登录直接跳转到登录页面提示用户登录。 再访问localhost:8080/add可以看到add页面如图5.2所示。之所以能够在没有登录的情况下看到add页面是因为Spring Security配置了未登录时可以访问/add这个链接。配置在WebSecurityConfig.java的代码如下 .antMatchers(/add/**).permitAll() 这个代码的含义是所有以/add开头的链接都允许访问因此可以看到add页面。 同理访问localhost:8080/css/my.css会返回项目的静态文件my.css因为在WebSecurity-Config中配置了静态文件的访问权限。 /* 所有的静态文件可以访问 */ .antMatchers(/js/**,/css/**,/images/**).permitAll() 所以js、css和images文件夹下的所有文件可以直接获取不会有任何校验访问结果如图5.3所示。 现在输入用户名admin和密码123456登录系统登录成功后的页面如图5.4所示因为在LoginSuccessHandler中配置了登录成功后的跳转页面代码即response.sendRedirect (/home)所以登录成功后直接跳转到了home页面。 Spring Security适配器 Spring大量使用适配器模式适配器的好处是当选择性地修改一部分配置时不用覆盖其他不相关的配置Spring Security常用的适配器有 WebSecurityConfigurerAdapter。在开发中可以选择覆盖部分自定义的配置从而快速完成开发。 设计模式中适配器模式的结构如图5.5所示。 适配器模式有3个类分别是Adapter适配者类、Target目标类和ObjectAdapter适配器可以通过这3个类实现适配器的相关功能。 在Spring Security框架中 WebSecurityConfigurerAdapter类图如图5.6所示。 在图5.6中SecurityBuilder、SecurityConfigurer和SecurityBuilder这3个类非常重要它们是用来构建过滤器链的在用HttpSecurity实现SecurityBuilder时传入的泛型是 DefaultSecurityFilterChain因此SecurityBuilder.build()用来构建过滤器链而WebSecurity- Configurer用来配置WebSecurity。 在 WebSecurityConfigurerAdapter中有两个方法非常重要下面分别介绍。 1第一个是init()方法其部分源码如下 public void init(final WebSecurity web) throws Exception { final HttpSecurity http getHttp(); web.addSecurityFilterChainBuilder(http).postBuildAction(() - { FilterSecurityInterceptor securityInterceptor http .getSharedObject(FilterSecurityInterceptor.class); web.securityInterceptor(securityInterceptor); }); } 首先init()方法调用了getHttp()方法其作用是进行HttpSecurity的初始化其部分源码如下 SuppressWarnings({ rawtypes, unchecked }) protected final HttpSecurity getHttp() throws Exception { if (http ! null) { return http; } AuthenticationEventPublisher eventPublisher getAuthenticationEventPublisher(); localConfigureAuthenticationBldr.authenticationEventPublisher(eventPub lisher); AuthenticationManager authenticationManager authenticationManager(); authenticationBuilder.parentAuthenticationManager(authenticationManage r); MapClass?, Object sharedObjects createSharedObjects(); http new HttpSecurity(objectPostProcessor, authenticationBuilder, sharedObjects); if (!disableDefaults) { // formatter:off http .csrf().and() .addFilter(new WebAsyncManagerIntegrationFilter()) .exceptionHandling().and() .headers().and() .sessionManagement().and() .securityContext().and() .requestCache().and() .anonymous().and() .servletApi().and() .apply(new DefaultLoginPageConfigurer()).and() .logout(); // formatter:on ClassLoader classLoader this.context.getClassLoader(); ListAbstractHttpConfigurer defaultHttpConfigurers SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader); for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) { http.apply(configurer); } } configure(http); return http; } 在初始化完成后init()方法调用了configure()方法配置默认的拦截器当完成HttpSecurity初始化后将HttpSecurity放入WebSecurity中最终保存在WebSecurity的 securityFilterChainBuilders集合中。configure()方法的部分源码如下 /** * 覆盖此方法以配置{link HttpSecurity}。 通常子类不建议通过调用super来调用此方法因为它可能会覆盖它们的配置。默认配置如下 * * pre * http.authorizeRequests().anyRequest().authenticated().and().formLogin( ).and().httpBasic(); * /pre * * 任何需要防御常见漏洞的端点都可以在这里指定包括公共的端点 * See {link HttpSecurity#authorizeRequests} and the permitAll()authorization rule * 更多关于公共端点的详细信息 * * param http the {link HttpSecurity} to modify * throws Exception if an error occurs */ // formatter:off protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and() .formLogin().and().httpBasic(); } 2另外一个非常重要的方法是前面提到的configure()方法。可以看到抽象类 WebSecurityConfigurerAdapter中的configure是个protect()方法开发者可以新建类或继承此类后实现该方法从而实现业务逻辑。 在当前项目中自定义的WebSecurityConfig类继承了 WebSecurityConfigurerAdapter()方法实现了空的configure()方法并配置了当前项目的登录和拦截信息。当前方法的入参是HttpSecurity可以使用HttpSecurity的builder构建方式来灵活制定访问策略。Http- Security的常用方法参见表5.1。 表5.1 HttpSecurity的常用方法 实战用户授权 在Spring Security中可以设置不同的用户拥有不同的角色同时不同的角色有不同的权限。下面举例说明。 修改HomeController.java文件增加一个/home2方法增加的代码如下 GetMapping(/home2) public String home2(){ return home2; } 修改WebSecurityConfig.java文件增加配置属性 /** * 授权赋予用户角色基于内存授权 */ Override protected UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager new InMemoryUserDetailsManager(); manager.createUser(User.withUsername(admin).password(123456). roles(admin).build()); return manager; } 修改WebSecurityConfig.java中的configure()方法增加/home2连接的 角色权限配置 // 授权配置 http.authorizeRequests() //可以访问所有静态文件 .antMatchers(/js/**,/css/**,/images/**).permitAll() //可以访问所有以/add开头的add页面 .antMatchers(/add/**).permitAll() .antMatchers(/home2).hasRole(user) .anyRequest().fullyAuthenticated(); 重启项目登录之后访问localhost:8080/home2结果如图5.7所示。因为当前用户没有权限所以访问报错。 Spring Security核心类 Spring Security框架中最核心的接口类是AuthenticationManager其部分源码如下 Authentication authenticate(Authentication authentication) throws AuthenticationException; AuthenticationManager是用来处理认证Authentication请求的基本接口。这个接口定义了方法authenticate()此方法只接收一个代表认证请求的Authentication对象作为参数如果认证成功则会返回一个封装了当前用户权限等信息的Authentication对象否则认证无法通过。 AuthenticationManager接口有两个重要的实现。 AuthenticationManagerDelegator是一个委托类由SecurityBuilder接口的子类来配置生成一个身份管理器另外一个实现类是ProviderManager此类的部分源码如下 public class ProviderManager implements AuthenticationManager, Message SourceAware, InitializingBean { private ListAuthenticationProvider providers Collections.emptyList(); private AuthenticationManager parent;public ProviderManager(AuthenticationProvider... providers) { this(Arrays.asList(providers), null); } /** * 使用给定的{link AuthenticationProvider}构造一个{link ProviderManager} * * param providers the {link AuthenticationProvider}s to use */ public ProviderManager(ListAuthenticationProvider providers) { this(providers, null); } /** * 使用给定的参考构造一个{link ProviderManager} * * param providers the {link AuthenticationProvider}s to use * param parent a parent {link AuthenticationManager} to fall back to */ public ProviderManager(ListAuthenticationProvider providers, AuthenticationManager parent) { Assert.notNull(providers, providers list cannot be null); this.providers providers; this.parent parent; checkState(); } } 在此类中构造函数有ListAuthenticationProvider providers它的作用是真正地完成认证工作。Spring Security有多种认证方式如邮箱登录、手机号登录和第三方登录等只要一个认证成功了就表示认证成功。 Spring Security的验证机制 核心类AuthenticationManager调用其他的实现类进行认证。在SpringSecurity中提供认证功能的接口是 org.springframework.security.authentication.AuthenticationProvider。 该接口有两个方法authenticate()方法用来认证处理返回一个authentication的实现类代表认证成功supports()方法表示当前身份提供者支持认证什么类型的身份信息如果支持返回true才会执行authenticate()方法进行身份认证。该接口的部分源码如下 public interface AuthenticationProvider { Authentication authenticate(Authentication authentication) throws AuthenticationException; boolean supports(Class? authentication); } AuthenticationProvider接口有几个常用的实现类用来实现认证类型的具体方式包括 AbstractUserDetailsAuthenticationProvider、DaoAuthenticationProvider和RememberMe- AuthenticationProvider。 DaoAuthenticationProvider的作用是从数据源中加载身份信息其类图如图5.8所示。 RememberMeAuthenticationFilter的作用是当用户没有登录而直接访问资源时首先从cookie中查找用户信息如果Spring Security能够识别出用户提供的remember me cookie则不用再输入用户名和密码表示用户已经认证成功。如图5.9所示为RememberMeAuthenticationProvider类图。 Spring Security的认证流程如下 1从 WebSecurityConfigurerAdapter认证配置的configure(HttpSecurity http)方法进入并添加拦截器addFilterBefore。 2进入 AbstractAuthenticationProcessingFilter拦截器的attemptAuthentication方法指定认证对象AbstractAuthenticationToken。 3执行AuthenticationProvider认证逻辑根据supports的判断对认证的目标对象选择一个拦截器进行认证进入具体的认证逻辑方法authenticate()。 4如果认证成功则进入拦截器的successfulAuthentication()方法如果认证失败则进入拦截器的 unsuccessfulAuthentication方法()。 5对认证结果进行处理。 认证成功的逻辑进入 SimpleUrlAuthenticationSuccessHandler的onAuthentication-Success()方法。 认证失败的逻辑进入 SimpleUrlAuthenticationFailureHandler的onAuthentication-Failure()方法。 6将数据封装在ObjectMapper对象中后即可返回结果。
http://www.dnsts.com.cn/news/35661.html

相关文章:

  • 网站运维工作内容公司网站做好了怎么做排名
  • 开个小网站要怎么做政务网站开发理念
  • 大型门户网站建设多少钱网站版权该怎么做呢
  • 公司网站设计与开发wordpress相册汉化版
  • 百度门户网站wordpress百度推送代码加统计
  • 湖南建设资质申请网站成都网站开发公司有哪些
  • 微信视频网站怎么做的好处免费网络连接软件
  • 建设部的网站哔哩网站开发需求分析模板
  • 乐都网站建设公司网站建站企业
  • 企业网站用免费程序比较有名的个人网站
  • 网站建设的关注点怎么做免费的网站
  • 在对方网站做友情链接微信营销课
  • 网站建设属于什么经营类型新媒体营销的概念
  • 湖南网站推广专业做家居的网站
  • 阿里云域名注册好了怎么做网站企业网站建设服务
  • 网站建设前期调研公司汇报大连建设网信息公开
  • 垂直网站二次开发什么意思
  • 丽水网站开发公司电话软文发布平台媒体
  • 帝国CMS做的淘客网站网页制作哪家质量好
  • 西安微网站手机端网站建设的费用清单
  • 网站优化图片链接怎么做网页版企业邮箱
  • 网站主页面设计湖南平台网站建设哪里有
  • 湖北建设信息网站百度免费云服务器
  • 网站专题策划方案书企业宣传方式有哪些
  • 如何做网站联盟产品市场推广方案
  • 如何用eclipse做网站腾讯邮箱注册入口官网
  • 希腊网站后缀wordpress数据库调用文章
  • 企业网站托管哪家好商业网点消防规范
  • 网站宽度多少合适做网站哪间好
  • 为什么做红酒网站东营做网站哪里好