spring security的简单例子

1 pom.的主要文件 我引入的thymeleaf-extras-springsecurity5,springboot2.1.6 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

    <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>

    </dependency>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</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-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
2 controller
[@Controller](https://my.oschina.net/u/1774615)

public class KungfuController {

private final String PREFIX = "pages/";

@RequestMapping("/")

public String index() {

	System.out.println("hello word");
	
	return "welcome";
}

@RequestMapping("/userlogin")

public String loginPage() {

	return PREFIX+"login1";
}

@GetMapping("/level1/{path}")

public String level1(@PathVariable("path")String path) {

	return PREFIX+"level1/"+path;
}

@GetMapping("/level2/{path}")

public String level2(@PathVariable("path")String path) {

	return PREFIX+"level2/"+path;
}

@GetMapping("/level3/{path}")

public String level3(@PathVariable("path")String path) {

	return PREFIX+"level3/"+path;
}

}

//配置下

@EnableWebSecurity public class mySecurity extends WebSecurityConfigurerAdapter {

//为啥引入这个bean ,因为在securety在5.0后使用系统的登录模板,默认把密码给加密啦,这个写的是不让密码加密

@Bean
public static NoOpPasswordEncoder passwordEncoder() {

    return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}


protected void configure(HttpSecurity http) throws Exception {

   //定制请求的授权规则
    http.authorizeRequests().antMatchers("/").permitAll()
	
            .antMatchers("/level1/**").hasRole("VIP1")
			
            .antMatchers("/level2/**").hasRole("VIP2")
			
            .antMatchers("/level3/**").hasRole("VIP3");
			
    //开启自动登录的功能
	
 http.formLogin();
 
 //开启自动配置的注销功能
 
 http.logout().logoutSuccessUrl("/");
 
}


public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication().withUser("mao").password("123").roles("VIP1","VIP2")
	
            .and().withUser("zhang").password("123").roles("VIP1","VIP3").and()
			
            .withUser("li").password("123").roles("VIP2","VIP3");
			
}

} //该模板都是尚学堂的

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org"

  xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<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 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> </html> 参考文献: 【1】https://docs.spring.io/spring-security/site/docs/current/guides/html5/helloworld-boot.html

【2】尚学堂

【3】https://www.jianshu.com/p/9e7792d767b2

转载于:https://my.oschina.net/u/2511906/blog/3074537

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 是一个强大的开源框架,用于提供全面的身份验证(Authentication)和授权(Authorization)解决方案,常用于Java Web应用程序中保护资源访问。它简化了处理用户登录、权限控制以及会话管理等安全相关的任务。 简单授权Demo通常涉及以下几个步骤: 1. 添加依赖:首先在你的Spring Boot项目中添加Spring Security的依赖。如果你使用Maven,可以在pom.xml中添加: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置WebSecurityConfigurerAdapter:创建一个`WebSecurityConfigurerAdapter`子类,并覆盖`configure(HttpSecurity http)`方法,设置基本的安全配置,如登录页面、默认登录处理器等: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login", "/register").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .failureUrl("/login?error") .and() .logout() .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } @Bean public UserDetailsService userDetailsServiceBean() { // 注册用户服务,这里是示例,实际应用中可能需要从数据库获取 return new InMemoryUserDetailsManager(Arrays.asList( new User("user", "password", AuthorityUtils.createAuthorityList("USER")) )); } } ``` 在这个例子中,我们允许"/login"和"/register"路径无需身份验证,所有其他请求都需要认证。登录失败后会被重定向到"/login?error"。 3. 用户认证:定义一个`UserDetailsService`实现,它负责从数据库或内存中加载用户信息进行验证。这里使用的是内存中的简单例子。 4. 创建Controller和视图:定义一个控制器,处理登录请求并渲染登录页面。例如: ```java @Controller public class LoginController { @GetMapping("/login") public String loginPage() { return "login"; } @PostMapping("/login") public String handleLogin(@RequestParam String username, @RequestParam String password, Model model) { // 这里只是一个简单的示例,实际应用中应检查用户名密码是否正确 if ("user".equals(username) && "password".equals(password)) { return "redirect:/"; } else { model.addAttribute("error", "Invalid credentials"); return "login"; } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值