git init
gradle wrapper ./gradlew build (or for windows ./gradlew.bat build)
package habraspring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @ComponentScan @EnableJpaRepositories(basePackages = {"habraspring"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
#settings for database spring.datasource.url = jdbc: mysql: // localhost / forhabrahabr spring.datasource.username = root spring.datasource.password = spring.datasource.driver-class-name = com.mysql.jdbc.Driver #turned on to enable lazy loading spring.jpa.properties.hibernate.enable_lazy_load_no_trans = true
15:24:47: Executing external task 'bootRun' ... : compileJava UP-TO-DATE : processResources : classes : findMainClass : bootRun . ____ _ __ _ _ / \\ / ___'_ __ _ _ (_) _ __ __ _ \ \ \ \ (() \ ___ | '_ |' _ | | '_ \ / _` | \ \ \ \ \\ / ___) | | _) | | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __, | / / / / ========= | _ | ============== | ___ / = / _ / _ / _ / :: Spring Boot :: (v1.2.5.RELEASE) 2015-07-11 14: 24: 49.180 INFO 12590 --- [main] habraspring. Application: Starting Application on MacBook-Pro-Maksim.local with PID 12590 (/ Users / admin / IdeaProjects / ForHabrahabr / build / classes / main started by admin in / Users / admin / IdeaProjects / ForHabrahabr) 2015-07-11 14: 24: 49.230 INFO 12590 --- [main] ationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2eda0940: startup date [Sat Jul 11 ​​14:24:49 MSK 2015]; root of context hierarchy 2015-07-11 14: 24: 50.029 INFO 12590 --- [main] osbfsDefaultListableBeanFactory: Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = true; primary = false; factoryBeanName = org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration; factoryMethodName = beanNameViewResolver; initMethodName = null; destroyMethodName = (inferred); [org / springframework / boot / autoconfigure / web / ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration.class]] [Root bean: class [null]; scope =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = true; primary = false; factoryBeanName = org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter; factoryMethodName = beanNameViewResolver; initMethodName = null; destroyMethodName = (inferred); defined in class path resource [org / springframework / boot / autoconfigure / web / WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter.class]] 2015-07-11 14: 24: 50.701 INFO 12590 --- [main] trationDelegate $ BeanPostProcessorChecker: bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransformat "class $$ 1f1e9ae] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2015-07-11 14: 24: 50.727 INFO 12590 --- [main] trationDelegate $ BeanPostProcessorChecker: Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not allowed for example: not eligible for auto-proxying) 2015-07-11 14: 24: 50.741 INFO 12590 --- [main] trationDelegate $ BeanPostProcessorChecker: Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] for example: not eligible for auto-proxying) 2015-07-11 14: 24: 50.746 INFO 12590 --- [main] trationDelegate $ BeanPostProcessorChecker: Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionerataerataeraftArte.staframework.transaction.config. eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2015-07-11 14: 24: 51.168 INFO 12590 --- [main] sbcetTomcatEmbeddedServletContainer: Tomcat initialized with port (s): 8080 (http) 2015-07-11 14: 24: 51.408 INFO 12590 --- [main] o.apache.catalina.core.StandardService: Starting service Tomcat 2015-07-11 14: 24: 51.409 INFO 12590 --- [main] org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat / 8.0.23 2015-07-11 14: 24: 51.601 INFO 12590 --- [ost-startStop-1] oaccC [Tomcat]. [Localhost]. [/]: Initializing Spring embedded WebApplicationContext 2015-07-11 14: 24: 51.601 INFO 12590 --- [ost-startStop-1] osweb.context.ContextLoader: Root WebApplicationContext: initialization completed 2374 ms 2015-07-11 14: 24: 52.570 INFO 12590 --- [ost-startStop-1] basAuthenticationManagerConfiguration: Using default security password: bd1659e1-4c49-43a2-9fd6-2ca7d46e9e23 2015-07-11 14: 24: 52.614 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating filter chain: Ant [pattern = '/ css / **'], [] 2015-07-11 14: 24: 52.614 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating filter chain: Ant [pattern = '/ js / **'], [] 2015-07-11 14: 24: 52.614 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating filter chain: Ant [pattern = '/ images / **'], [] 2015-07-11 14: 24: 52.614 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating filter chain: Ant [pattern = '/ ** / favicon.ico'], [] 2015-07-11 14: 24: 52.614 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating filter chain: Ant [pattern = '/ error'], [] 2015-07-11 14: 24: 52.650 INFO 12590 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain: Creating a filter chain: OrRequestMatcher [requestMatchers = [Ant [pattern = '/ **']]], [org .springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter @ 5854c7d0, org.springframework.security.web.context.SecurityContextPersistenceFilter@874f491, and of up to about 20 nights of max total. .web.authentication.logout.LogoutFilter @ 609329b3, org.springframework.security.web.authentication. .SecurityContextHolderAwareRequestFilter @ a3153e3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1b8b1dc9, org.springframework.access.access.access.access.access.access.access.access.asn.acquireFileter.ab.Abl.Anl.Anl. 4, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1fb86c05] 2015-07-11 14: 24: 52.723 INFO 12590 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'characterEncodingFilter' to: [/ *] 2015-07-11 14: 24: 52.724 INFO 12590 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'hiddenHttpMethodFilter' to: [/ *] 2015-07-11 14: 24: 52.724 INFO 12590 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'springSecurityFilterChain' to: [/ *] 2015-07-11 14: 24: 52.724 INFO 12590 --- [ost-startStop-1] osbceServletRegistrationBean: Mapping servlet: 'dispatcherServlet' to [/] 2015-07-11 14: 24: 53.410 INFO 12590 --- [main] j.LocalContainerEntityManagerFactoryBean: Building JPA container EntityManagerFactory for persistence unit 'default' 2015-07-11 14: 24: 53.425 INFO 12590 --- [main] o.hibernate.jpa.internal.util.LogHelper: HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2015-07-11 14: 24: 53.500 INFO 12590 --- [main] org.hibernate.Version: HHH000412: Hibernate Core {4.3.10.Final} 2015-07-11 14: 24: 53.503 INFO 12590 --- [main] org.hibernate.cfg.Environment: HHH000206: hibernate.properties not found 2015-07-11 14: 24: 53.505 INFO 12590 --- [main] org.hibernate.cfg.Environment: HHH000021: Bytecode provider name: javassist 2015-07-11 14: 24: 53.628 INFO 12590 --- [main] o.hibernate.annotations.common.Version: HCANN000001: Hibernate Commons Annotations {4.0.5.Final} 2015-07-11 14: 24: 53.711 INFO 12590 --- [main] org.hibernate.dialect.Dialect: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 2015-07-11 14: 24: 53.774 INFO 12590 --- [main] ohhiast.ASTQueryTranslatorFactory: HHH000397: Using ASTQueryTranslatorFactory 2015-07-11 14: 24: 54.244 INFO 12590 --- [main] swsmmaRequestMappingHandlerAdapter: Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2eda0940: launch date [Sat Jul 11 ​​14:24 MSK 2015]; root of context hierarchy 2015-07-11 14: 24: 54.328 INFO 12590 --- [main] swsmmaRequestMappingHandlerMapping: Mapped "{[/ error]}": java.util.Map <java.lang.String , java.lang.Object >> org.springframework.boot.autoconfigure.web.BasicErrorController.error (javax.servlet.http.HttpServletRequest) 2015-07-11 14: 24: 54.328 INFO 12590 --- [main] swsmmaRequestMappingHandlerMapping: Mapped "{[/ error], produces = [text / html]}" for public org.springframework.web.servlet.ModelAndView org. springframework.boot.autoconfigure.web.BasicErrorController.errorHtml (javax.servlet.http.HttpServletRequest) 2015-07-11 14: 24: 54.356 INFO 12590 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/ webjars / **] for class of [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2015-07-11 14: 24: 54.357 INFO 12590 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/ **] for handler type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2015-07-11 14: 24: 54.393 INFO 12590 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/**/favicon.ico] [class org.springframework.web.servlet.resource. ResourceHttpRequestHandler] 2015-07-11 14: 24: 54.723 INFO 12590 --- [main] osjeaAnnotationMBeanExporter: Registering beans for JMX exposure on startup 2015-07-11 14: 24: 54.800 INFO 12590 --- [main] sbcetTomcatEmbeddedServletContainer: Tomcat started on port (s): 8080 (http) 2015-07-11 14: 24: 54.803 INFO 12590 --- [main] habraspring.Application: Started Application in 5.945 seconds (JVM running for 6.529)
package habraspring.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/").setViewName("home"); } }
package habraspring.config; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll(); } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Habrahabr</title> </head> <body> <h1>Welcome!</h1> <p>Yours home page.</p> </body> </html>
Welcome! Yours home page.
package habraspring.entities; import javax.persistence.*; @Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } protected User(){} public User(String name, String pass) { username = name; password = pass; } }
package habraspring.repositories; import habraspring.entities.User; import org.springframework.data.repository.CrudRepository; public interface UsersRepository extends CrudRepository<User, Long> { User findByUsername(String username); }
package habraspring.utils; import habraspring.entities.User; import habraspring.repositories.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Service public class MySQLUserDetailsService implements UserDetailsService { @Autowired UsersRepository users; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails loadedUser; try { User client = users.findByUsername(username); loadedUser = new org.springframework.security.core.userdetails.User( client.getUsername(), client.getPassword(), DummyAuthority.getAuth()); } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } return loadedUser; } static class DummyAuthority implements GrantedAuthority { static Collection<GrantedAuthority> getAuth() { List<GrantedAuthority> res = new ArrayList<>(1); res.add(new DummyAuthority()); return res; } @Override public String getAuthority() { return "USER"; } } }
package habraspring.config; import habraspring.utils.MySQLUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired private MySQLUserDetailsService mySQLUserDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(mySQLUserDetailsService); } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Secret page</title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Sign Out"/> </form> </body> </html>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Login page</title> </head> <body> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <form th:action="@{/login}" method="post"> <div><label> User Name : <input type="text" name="username"/> </label></div> <div><label> Password: <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign In"/></div> </form> </body> </html>
registry.addViewController("/login").setViewName("login"); registry.addViewController("/secret").setViewName("secret");
package habraspring.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/").setViewName("home"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/secret").setViewName("secret"); } }
package habraspring.config; import habraspring.utils.MySQLUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired private MySQLUserDetailsService mySQLUserDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(mySQLUserDetailsService); } }
.authorizeRequests() .antMatchers("/", "/home").permitAll()
.anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll();
@Autowired private MySQLUserDetailsService mySQLUserDetailsService;
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(mySQLUserDetailsService); }
package habraspring.utils; import habraspring.entities.User; import habraspring.repositories.UsersRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Service public class MySQLUserDetailsService implements UserDetailsService { @Autowired UsersRepository users; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails loadedUser; try { User client = users.findByUsername(username); loadedUser = new org.springframework.security.core.userdetails.User( client.getUsername(), client.getPassword(), DummyAuthority.getAuth()); } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } return loadedUser; } static class DummyAuthority implements GrantedAuthority { static Collection<GrantedAuthority> getAuth() { List<GrantedAuthority> res = new ArrayList<>(1); res.add(new DummyAuthority()); return res; } @Override public String getAuthority() { return "USER"; } } }
@Autowired UsersRepository users; .... User client = users.findByUsername(username);
loadedUser = new org.springframework.security.core.userdetails.User( client.getUsername(), client.getPassword(), DummyAuthority.getAuth());
package habraspring.entities; import javax.persistence.*; @Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } protected User(){} public User(String name, String pass) { username = name; password = pass; } }
@Entity @Table(name="users") public class User {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String username; private String password;
protected User(){} public User(String name, String pass) { username = name; password = pass; }
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.5.RELEASE") classpath 'mysql:mysql-connector-java:5.1.34' } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' jar { baseName = 'gs-rest-service' version = '0.1.0' } repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-security") compile("org.springframework.boot:spring-boot-starter-thymeleaf") compile 'mysql:mysql-connector-java:5.1.31' compile 'commons-dbcp:commons-dbcp:1.4' testCompile("org.springframework:spring-test") testCompile("junit:junit") testCompile 'org.springframework.security:spring-security-test:4.0.1.RELEASE' } task wrapper(type: Wrapper) { gradleVersion = '2.3' }
dependencies { compile("org.springframework.boot:spring-boot-starter-web") - Spring MVC compile("org.springframework.boot:spring-boot-starter-data-jpa") - Spring Jpa( ) compile("org.springframework.boot:spring-boot-starter-security") - Spring Security compile("org.springframework.boot:spring-boot-starter-thymeleaf") - resources/tempates compile 'mysql:mysql-connector-java:5.1.31' - mysql to spring compile 'commons-dbcp:commons-dbcp:1.4'
testCompile("org.springframework:spring-test") testCompile("junit:junit") testCompile 'org.springframework.security:spring-security-test:4.0.1.RELEASE'
Source: https://habr.com/ru/post/262323/
All Articles