二、SpringSecurity+auth2.0系列(form 表单模式)

此模块基于模块一,读者可阅读本专栏

Form 表单模式 适合于传统模式项目 前端和后端都是我们java开发
修改配置完整代码如下

package com.thunisoft.spring_security.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
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.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 新增 HttpSecurity基础配置配置
         */
        // http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();


        /**
         * 新增HttpSecurity formLogin模式
         */
        //http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember")
                .antMatchers("/editMember").hasAnyAuthority("editMember").
               // antMatchers("/**").fullyAuthenticated().and().formLogin()
                antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
                .loginPage("/login").and().csrf().disable();

    }


    /*
    * 新增授权账户
    * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //新增一个用户为orange和admin用户,权限不一样
        auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("addMember","delMember","editMember","showMember");
        auth.inMemoryAuthentication().withUser("orange").password("orange").authorities("showMember");
    }


    /**
     * 密码不做任何处理
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }





}

配置权限策略
在企业管理系统平台中,会拆分成n多个不同的账号,
每个账号对应不同的接口访问权限,
比如
账号admin所有接口都可以访问;
orange账户 只能访问/addMember接口;
代码如上代码中所示

如何修改403权限不足页面
在config包下新建配置类,代码如下

package com.thunisoft.spring_security.config;


import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class WebServerAutoConfiguration {
    /**
     * 授权失败调转页面
     * @return
     */
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}

在controller包下新建errorcontroller类
代码如下:

package com.thunisoft.spring_security.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ErrorController {



    @RequestMapping("/error/403")
    public String error403() {
        return "您当前访问的接口权限不足!";
    }


    @RequestMapping("/error/400")
    public String error400() {
        return "您当前请求异常!";
    }

    @RequestMapping("/error/401")
    public String error401() {
        return "您的状态未认证!";
    }

    @RequestMapping("/error/404")
    public String error404() {
        return "页面未查询到!";
    }

    @RequestMapping("/error/415")
    public String error415() {
        return "请求格式错误!";
    }

    @RequestMapping("/error/500")
    public String error500() {
        return "服务器内部错误!";
    }

}

登陆页面
包controller新建登录类
代码如下

package com.thunisoft.spring_security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

导入freemarker依赖

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

自定义登录页面login.ftl
在resource下新建templates,新建这个文件

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;
            charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

<h1>权限控制登陆系统</h1>
<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="username"/> <br>
    <span>用户密码</span><input type="password" name="password"/> <br>
    <input type="submit" value="登陆">

</form>

<#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>

配置application.yml
次数为配置页面的参数

spring:
  freemarker:
    settings:
      classic_compatible: true
      datetime_format: yyy-MM-dd HH:mm
      number_format: 0.##
    suffix: .ftl
    template-loader-path: classpath:/templates

运行项目,进行登录测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@我不是大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值