springboot和spring security简单使用

整理自是尚硅谷springboot高级

配置类(最重要的了)

@EnableWebSecurity//这个注解组合注解里面有@Configuration 所以不要配置@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //重写认证方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/").permitAll() //放行这个请求
            .antMatchers("/level1/**").hasRole("vip1") //level1下的页面需要vip1这个角色才可以访问
            .antMatchers("/level2/**").hasRole("vip2")
            .antMatchers("/level3/**").hasRole("vip3");

        //开启自动配置的登录功能,就是你没登陆或者没有权限,给你创建一个登录页面
           // http.formLogin()
        //开启自动配置的登录功能,用自己的登录页 路径loginPage("/userlogin")
        //passwordParameter  usernameParameter 自定义表单的name值(默认username password)
        http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");
        //设置退出及退出成功后的页面(前台需要post方法提交)
      /*  <form th:action="@{/logout}" method="post">
		    <input type="submit" value="注销"/>
	       </form>*/
         http.logout().logoutSuccessUrl("/");
         //开启记住我功能,前端会添加个复选框记住我和实现记住我功能,无需自己实现
         http.rememberMe().rememberMeParameter("rember");

    }

   //重写授权方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //创建一个用户,给其赋值和赋予角色多个角色逗号隔开
        auth.inMemoryAuthentication()
             .withUser("zs").password("123").roles("vip1")
             .and()
             .withUser("ls").password("123").roles("vip2","vip1")
             .and()
             .withUser("ww").password("123").roles("vip3","vip1") ;
    }
  /*  @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }*/
}

pom文件

        <!---选择1.x版本--->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
                <!---选择3版本-->
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
             <!---选择3版本-->
		<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
            <!---选择2版本-->
		<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

welcom.html

<!---命名空间有写代码提示---->
<html xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
	<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
	<h2>欢迎您: <span style="color: red" sec:authentication="name"></span> 您的角色有 <span  sec:authentication="principal.authorities"></span></h2>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="注销"/>
	</form>
</div>
<hr>

<div sec:authorize="hasRole('vip1')">
	<h3>普通武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level1/1}">罗汉拳</a></li>
		<li><a th:href="@{/level1/2}">武当长拳</a></li>
		<li><a th:href="@{/level1/3}">全真剑法</a></li>
	</ul>
</div>

<div sec:authorize="hasRole('vip2')">
	<h3>高级武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level2/1}">太极拳</a></li>
		<li><a th:href="@{/level2/2}">七伤拳</a></li>
		<li><a th:href="@{/level2/3}">梯云纵</a></li>
	</ul>
</div>
<div sec:authorize="hasRole('vip3')">
	<h3>绝世武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level3/1}">葵花宝典</a></li>
		<li><a th:href="@{/level3/2}">龟派气功</a></li>
		<li><a th:href="@{/level3/3}">独孤九剑</a></li>
	</ul>
</div>
</body>

自定义登录页面

<body>
	<h1 align="center">欢迎登陆武林秘籍管理系统</h1>
	<hr>
	<div align="center">
		<form th:action="@{/userlogin}" method="post">
			用户名:<input name="user"/><br>
			密码:<input name="pwd"><br/>
			<input type="submit" value="登陆">
			<input type="checkbox" name="rember">记住我
		</form>
	</div>
</body>

这个level1,level2,level3目录类似如此,没啥内容命名相同即可

控制器,跳转相关页面(KungfuController)

@Controller
public class KungfuController {
	private final String PREFIX = "pages/";
	/**
	 * 欢迎页
	 * @return
	 */
	@GetMapping("/")
	public String index() {
		return "welcome";
	}
	
	/**
	 * 登陆页
	 * @return
	 */
	@GetMapping("/userlogin")
	public String loginPage() {
		return PREFIX+"login";
	}
	
	
	/**
	 * level1页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level1/{path}")
	public String level1(@PathVariable("path")String path) {
		return PREFIX+"level1/"+path;
	}
	
	/**
	 * level2页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level2/{path}")
	public String level2(@PathVariable("path")String path) {
		return PREFIX+"level2/"+path;
	}
	
	/**
	 * level3页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level3/{path}")
	public String level3(@PathVariable("path")String path) {
		return PREFIX+"level3/"+path;
	}


}
扫描二维码关注公众号,回复: 3623914 查看本文章

截图

猜你喜欢

转载自blog.csdn.net/loveyour_1314/article/details/83003321