spring security-认证与授权

1、引入 Spring Security 模块

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

2.前端页面(给出部分代码,使用了bootstrap这个ui框架)
注:表单提交地址必须为controller的跳转地址

<form role="form" class="form_div" action="/login" method="post" onsubmit="return GetDom();">
            <div class="form-group">
                <label for="user" class="col-lg-3 control-label">账号</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" th:name="user" id="user" placeholder="请输入账号">
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-lg-3 control-label">密码</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="password" th:name="password" placeholder="请输入密码">
                </div>
            </div>
            <div id="mes_div" class="form-group">
                <div id="div_prompt"  style="display: none;">
                    <div class="alert alert-danger alert-dismissible" style="width: 300px;height: 50px;margin-left: 90px;">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong th:text="${result}"></strong>
                    </div>
                </div>
            </div>
            <div id="div_button" >
                <button type="submit" class="btn btn-default" name="OK" id="OK" >登录</button>
                <a type="button" class="btn btn-default" th:href="@{/registered}">注册</a>
            </div>
        </form>

3.写页面跳转的controller

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

@Controller
public class JumpController {

    @RequestMapping("/index")
    public String goindex(){
        return "index";
    }
    @RequestMapping("/")
    public String gologin(){
        return "login";
    }

    @RequestMapping("/login")
    public String toLogin(){
        return "login";
    }
}

4.编写配置类
注销前端发送的请求:/logout

package com.shop.config;

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.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //将静态资源static中的文件夹过滤掉,全部通过,其他都拦截
        http.authorizeRequests().antMatchers("/css/**","/img/**","/js/**","/layui/**","/bootstrap-3.3.7/**").permitAll().anyRequest().authenticated();
	//将默认的登录页改成自己写的,修改前端input上的name属性(默认为username跟password,若不一样得修改),接着是成功后跳转的页面,以及登陆后允许全部访问        
        http.formLogin().loginPage("/login").usernameParameter("user").passwordParameter("password").successForwardUrl("/index").permitAll();
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        http.logout().logoutSuccessUrl("/");//注销登录返回首页
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //为方便测试,在内存中创建一个用户、密码、 权限都为pefung的用户,密码使用BCryptPasswordEncoder加密,登录的账号密码就为这几个
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("pefung").password(new BCryptPasswordEncoder().encode("pefung")).roles("pefung");
    }
}

5.授权
.antMatchers("/shouquan/**").hasRole(“vip1”):
shouquan路径下的文件需要有vip1的权限才能访问

http.authorizeRequests()
.antMatchers("/css/**","/img/**","/js/**","/layui/**","/bootstrap-3.3.7/**")
.permitAll()
.antMatchers("/shouquan/**").hasRole("vip1")
.anyRequest().authenticated();

此处的roles就是给该用户设置了pefung的权限,如权限设置成vip1,则用这个用户可访问上面的shouquan中的页面

 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //为方便测试,在内存中创建一个用户、密码、 权限都为pefung的用户,密码使用BCryptPasswordEncoder加密,登录的账号密码就为这几个
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("pefung").password(new BCryptPasswordEncoder().encode("pefung")).roles("pefung");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值