美文网首页
Spring Security(一):介绍以及项目搭建

Spring Security(一):介绍以及项目搭建

作者: 疏花 | 来源:发表于2019-07-19 20:54 被阅读0次

    一、介绍

    Spring Security是一个专注于为Java应用程序提供身份验证、授权和访问控制的功能强大且可高度自定义的框架。与所有Spring项目一样,Spring Security的真正强大之处在于它可以轻松扩展以满足自定义要求。
    Spring Security具有如下几个特征:

    • 对身份验证和授权的全面和可扩展的支持
    • 防止会话固定,点击劫持,跨站点请求伪造等攻击
    • Servlet API 集成
    • 可选的与Spring Web MVC的集成
    • 等等

    二、项目搭建及配置

    使用IDEA新建项目



    点击Next,随便配置group和artifact等



    下一步,引入需要的依赖
    spring security
    spring boot开发插件
    thymeleaf模板引擎
    Spring MVC

    下一步,点击finish



    完整目录结构及maven依赖

    新建home页面:src/main/resources/templates/home.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-springsecurity">
        <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>
    

    home页面中有一个/hello链接指向hello.html:
    src/main/resources/templates/hello.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>Hello World!</title>
        </head>
        <body>
            <h1>Hello world!</h1>
        </body>
    </html>
    

    配置Spring MVC:
    com.hermes.security.config.MvcConfig

    package com.hermes.security.config;
    
    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.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.factory.PasswordEncoderFactories;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    /**
     * @author: lzb
     * @create: 2019/07/19 21:33
     * @description:
     */
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder encoder;
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/", "/home").permitAll()
                    .anyRequest().authenticated()
                    .and()
                 .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                 .logout()
                    .permitAll();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .passwordEncoder(encoder)
                    .withUser("username")
                    .password(encoder.encode("password"))
                    .roles("USER");
        }
    
        /**
         * 此处需要配置密码编码器,否则可能产生
         * {@code There is no PasswordEncoder mapped for the id "null"}的错误
         *
         * @return 密码编码器
         */
        @Bean
        public PasswordEncoder passwordEncoder() {
            return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        }
    }
    
    

    WebSecurityConfig类使用@EnableWebSecurity注解以启用spring security的web安全支持,并提供了spring mvc集成,此外它扩展了WebSecurityConfigurerAdapter,重写了一些方法来进行web安全配置。

    configure(HttpSecurity)方法定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。

    当用户成功登录时,它们将被重定向到先前请求的需要身份认证的页面。有一个由 loginPage()指定的自定义“/登录”页面,每个人都可以查看它。

    对于configureGlobal(AuthenticationManagerBuilder) 方法,它将单个用户设置在内存中。该用户的用户名为“username”,密码为“password”,角色为“USER”。

    创建登录页面:
    templates/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>
    

    此页面提供了一个表单用于接收用户名和密码,spring security提供了一个拦截该请求并验证用户的过滤器,如果验证失败,该页面将重定向到/login?error,并显示相应错误信息。用户注销后,页面将重定向到/login?logout,页面显示登出成功消息。

    最后,提供一个显示当前用户名和登出的方法,更新hello.html,向当前用户打印一句hello,并包含一个注销表单:
    /templates/hello.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>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>
    

    启动应用

    启动com.hermes.security.SecurityApplication
    应用启动后, 在浏览器中访问 http://localhost:8080. 你可以访问到首页:

    首页
    点击click后跳转到hello页面,该页面是受保护的:
    hello页面
    输入用户名密码登录:
    登录成功
    点击sign out:
    登出成功

    至此,一个简单的基于spring security的web就搭建完成了。

    相关文章

      网友评论

          本文标题:Spring Security(一):介绍以及项目搭建

          本文链接:https://www.haomeiwen.com/subject/pjhelctx.html