本文共 11086 字,大约阅读时间需要 36 分钟。
org.springframework.boot spring-boot-starter-security
4.0.0 netkiller.cn api.netkiller.cn 0.0.1-SNAPSHOT jar api.netkiller.cn http://maven.apache.org UTF-8 1.8 org.springframework.boot spring-boot-starter-parent 1.3.0.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-devtools org.springframework.boot spring-boot-starter-test test org.springframework.data spring-data-mongodb org.springframework.data spring-data-oracle 1.0.0.RELEASE com.oracle ojdbc6 11.2.0.3 system ${basedir}/lib/ojdbc6.jar mysql mysql-connector-java org.springframework.boot spring-boot-starter-mail org.springframework.boot spring-boot-starter-velocity org.apache.velocity velocity com.google.code.gson gson compile junit junit test src org.springframework.boot spring-boot-maven-plugin maven-compiler-plugin 3.3 maven-war-plugin 2.6 WebContent false
src/main/resources/application.properties
添加默认用户,角色user,用户名neo,密码password
security.user.name=neosecurity.user.password=password security.user.role=USER
现在启动Application,然后尝试访问url,这时会弹出对话框,提示用户用户输入用户名与密码。使用上面的密码便可登陆。
package api;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.data.jpa.repository.config.EnableJpaRepositories;import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@SpringBootApplication@EnableAutoConfiguration@ComponentScan({ "api.config", "api.web", "api.rest", "api.service" })@EnableMongoRepositories@EnableJpaRepositoriespublic class Application { public @Bean WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }; } public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
注意WebSecurityConfigurer必须在 ComponentScan 的扫描范围
package api.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.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration@EnableWebSecuritypublic class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(). withUser("user1").password("secret1").roles("USER") .and(). withUser("user2").password("secret2").roles("USER") .and(). withUser("admin").password("secret").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().fullyAuthenticated(); http.httpBasic(); http.csrf().disable(); }}
@RestController@RequestMapping("/service")public class UserService { @RequestMapping(value = "/echo/{in}", method = RequestMethod.GET) public String echo(@PathVariable(value = "in") final String in, @AuthenticationPrincipal final UserDetails user) { return "Hello " + user.getUsername() + ", you said: " + in; }}
curl -u user:password http://172.16.0.20:8080/index.htmlcurl http://user:password@172.16.0.20:8080/index.html
MongoDB 为 Security 用户认证提供数据存储。
package mis.domain;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.index.Indexed;public class Administrator { @Id private String id; @Indexed(unique = true) private String username; private String password; private String authority; public Administrator() { // TODO Auto-generated constructor stub } public Administrator(String username, String password) { this.username = username; this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAuthority() { return authority; } public void setAuthority(String authority) { this.authority = authority; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", authority=" + authority + "]"; }}
package mis.repository;import org.springframework.data.mongodb.repository.MongoRepository;import mis.domain.Administrator;public interface AdministratorRepository extends MongoRepository{ public Administrator findByUsername(String username);}
package mis.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;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.core.authority.AuthorityUtils;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import mis.domain.Administrator;import mis.repository.AdministratorRepository;@Configurationclass GlobalAuthenticationConfigurer extends GlobalAuthenticationConfigurerAdapter { @Autowired AdministratorRepository administratorRepository; @Override public void init(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()); } @Bean UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Administrator administrator = administratorRepository.findByUsername(username); if (administrator != null) { return new User(administrator.getUsername(), administrator.getPassword(), AuthorityUtils.createAuthorityList(administrator.getAuthority())); } else { throw new UsernameNotFoundException("could not find the administrator '" + username + "'"); } } }; }}@Configuration@EnableWebSecuritypublic class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { public WebSecurityConfigurer() { // TODO Auto-generated constructor stub } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable(); // http.authorizeRequests().antMatchers("/", "/index.html", "/css/**", // "/js/**","/static/**","/setup.html").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login.html").permitAll().and().logout().permitAll().and().httpBasic(); // http.authorizeRequests().antMatchers("/**" // ).permitAll().and().httpBasic(); http.authorizeRequests().antMatchers("/ping", "/v1/*/ping", "/v1/public/**").permitAll().anyRequest().authenticated().and().rememberMe().and().httpBasic().and().csrf().disable(); }}
原文出处:Netkiller 系列 手札
本文作者:陈景峯 转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。