1.这里面安装这个
2.跑起来发现,给了我们一个密码
3.我们直接访问本地的localhost:8080/login,默认用户名是user
4. 这里设置默认的账号密码
5.我们新建一个security文件夹,DemoSecurityConfig类
package com.example18.example_18.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration public class DemoSecurityConfig { @Bean public InMemoryUserDetailsManager userDetailsManager(){ UserDetails join= User.builder() .username("john") .password("{noop}test123") .roles("EMPLOYEE") .build(); UserDetails mary= User.builder() .username("mary") .password("{noop}test123") .roles("EMPLOYEE","MANAGER") .build(); UserDetails susan= User.builder() .username("susan") .password("{noop}test123") .roles("EMPLOYEE","MANAGER","ADMIN") .build(); return new InMemoryUserDetailsManager(join,mary,susan); } }
6.我们访问发现没授权
把上面的账号密码输入,成功了
7.通过角色来分批管理,DemoSecurityConfig 类
package com.example18.example_18.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration public class DemoSecurityConfig { @Bean public InMemoryUserDetailsManager userDetailsManager(){ UserDetails join= User.builder() .username("john") .password("{noop}test123") .roles("EMPLOYEE") .build(); UserDetails mary= User.builder() .username("mary") .password("{noop}test123") .roles("EMPLOYEE","MANAGER") .build(); UserDetails susan= User.builder() .username("susan") .password("{noop}test123") .roles("EMPLOYEE","MANAGER","ADMIN") .build(); return new InMemoryUserDetailsManager(join,mary,susan); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http.authorizeHttpRequests(configurer -> configurer .requestMatchers(HttpMethod.GET,"/students").hasRole("MANAGER") ); // use HTTP Basic authentication http.httpBasic(Customizer.withDefaults()); //disable Cross site Request Forgery http.csrf(csrf -> csrf.disable()); return http.build(); } }
8.如何利用支持数据库的来查询
标签:spring,boot,springframework,User,import,org,security,UserDetails From: https://www.cnblogs.com/hechunfeng/p/18548146