开发实例(三)

tech2022-08-07  162

添加依赖

在项目pom.xml文件中添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> 在config下创建SpringSecurityConfig并添加代码

package com.example.demo.config; import org.springframework.context.annotation.Configuration; 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.builders.WebSecurity; 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; @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder(new MyPasswordEncoder()) .withUser("admin") .password(new MyPasswordEncoder().encode("123456")) .roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() .and() .logout().permitAll() .and() .formLogin(); http.csrf().disable(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**","/css/**","/image/**"); } } 在config里创建MyPasswordEncoder文件并添加代码 package com.example.demo.config; import org.springframework.security.crypto.password.PasswordEncoder; public class MyPasswordEncoder implements PasswordEncoder { final static String SALT = "123456"; @Override public String encode(CharSequence charSequence) { System.out.println(charSequence + SALT); return charSequence + SALT; } @Override public boolean matches(CharSequence charSequence, String s) { System.out.println("加密的密码:"+s); System.out.println("未加密的密码:"+charSequence); return s.equals(charSequence+SALT); } } 测试

访问http://localhost/demo/

访问http://localhost/demo/login

http://localhost/demo/list

最新回复(0)