Skip to content

Commit 5f9ef96

Browse files
gitterjim-Izhendrikse
authored andcommitted
manual authentication demo integration (eugenp#836)
* manual authentication demo integration * apply eclipse and security formatting rules * add content to readme file, for manual authentication demo
1 parent 19b4155 commit 5f9ef96

File tree

11 files changed

+230
-1
lines changed

11 files changed

+230
-1
lines changed

spring-security-client/README.MD

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,11 @@
1-
###The Course
1+
=========
2+
## Spring Security Authentication/Authorization Example Project
3+
4+
##The Course
25
The "REST With Spring" Classes: http://github.learnspringsecurity.com
6+
7+
### Relevant Articles:
8+
- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication)
9+
10+
### Build the Project
11+
mvn clean install

spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
99
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
1010
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
11+
import org.springframework.context.annotation.Profile;
1112

1213
@Configuration
1314
@EnableWebMvc
15+
@Profile("!manual")
1416
public class MvcConfig extends WebMvcConfigurerAdapter {
1517

1618
public MvcConfig() {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.context.annotation.Profile;
5+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
6+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
7+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8+
9+
@Configuration
10+
@EnableWebMvc
11+
@Profile("manual")
12+
public class MvcConfigManual extends WebMvcConfigurerAdapter {
13+
14+
@Override
15+
public void addViewControllers(ViewControllerRegistry registry) {
16+
registry.addViewController("/home").setViewName("home");
17+
registry.addViewController("/").setViewName("home");
18+
registry.addViewController("/hello").setViewName("hello");
19+
registry.addViewController("/login").setViewName("login");
20+
}
21+
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package org.baeldung.config;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
import javax.servlet.http.HttpServletResponse;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.security.authentication.AbstractAuthenticationToken;
10+
import org.springframework.security.authentication.AuthenticationManager;
11+
import org.springframework.security.authentication.BadCredentialsException;
12+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13+
import org.springframework.security.core.Authentication;
14+
import org.springframework.security.core.context.SecurityContextHolder;
15+
import org.springframework.security.web.authentication.WebAuthenticationDetails;
16+
import org.springframework.stereotype.Controller;
17+
import org.springframework.web.bind.annotation.RequestMapping;
18+
import org.springframework.web.bind.annotation.RequestMethod;
19+
import org.springframework.context.annotation.Profile;
20+
21+
/**
22+
* Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration)
23+
* (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc)
24+
*
25+
* @author jim clayson
26+
*/
27+
@Controller
28+
@Profile("manual")
29+
public class RegistrationController {
30+
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
31+
32+
@Autowired
33+
AuthenticationManager authenticationManager;
34+
35+
/**
36+
* For demo purposes this need only be a GET request method
37+
*
38+
* @param request
39+
* @param response
40+
* @return The view. Page confirming either successful registration (and/or
41+
* successful authentication) or failed registration.
42+
*/
43+
@RequestMapping(value = "/register", method = RequestMethod.GET)
44+
public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) {
45+
logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate.");
46+
47+
// Mocked values. Potentially could come from an HTML registration form,
48+
// in which case this mapping would match on an HTTP POST, rather than a GET
49+
String username = "user";
50+
String password = "password";
51+
52+
String view = "registrationSuccess";
53+
54+
if (requestQualifiesForManualAuthentication()) {
55+
try {
56+
authenticate(username, password, request, response);
57+
logger.debug("registerAndAuthenticate: authentication completed.");
58+
} catch (BadCredentialsException bce) {
59+
logger.debug("Authentication failure: bad credentials");
60+
bce.printStackTrace();
61+
view = "systemError"; // assume a low-level error, since the registration
62+
// form would have been successfully validated
63+
}
64+
}
65+
66+
return view;
67+
}
68+
69+
private boolean requestQualifiesForManualAuthentication() {
70+
// Some processing to determine that the user requires a Spring Security-recognized,
71+
// application-directed login e.g. successful account registration.
72+
return true;
73+
}
74+
75+
private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException {
76+
logger.debug("attempting to authenticated, manually ... ");
77+
78+
// create and populate the token
79+
AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
80+
authToken.setDetails(new WebAuthenticationDetails(request));
81+
82+
// This call returns an authentication object, which holds principle and user credentials
83+
Authentication authentication = this.authenticationManager.authenticate(authToken);
84+
85+
// The security context holds the authentication object, and is stored
86+
// in thread local scope.
87+
SecurityContextHolder.getContext().setAuthentication(authentication);
88+
89+
logger.debug("User should now be authenticated.");
90+
}
91+
92+
}

spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
import org.springframework.security.config.annotation.web.builders.WebSecurity;
77
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
88
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
import org.springframework.context.annotation.Profile;
910

1011
@Configuration
1112
@EnableWebSecurity
13+
@Profile("!manual")
1214
public class SecurityConfig extends WebSecurityConfigurerAdapter {
1315

1416
@Override
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.context.annotation.Profile;
6+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
11+
@Configuration
12+
@EnableWebSecurity
13+
@Profile("manual")
14+
public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter {
15+
16+
@Override
17+
protected void configure(HttpSecurity http) throws Exception {
18+
// @formatter:off
19+
http
20+
.authorizeRequests()
21+
.antMatchers("/", "/home", "/register").permitAll()
22+
.anyRequest().authenticated()
23+
.and()
24+
.formLogin()
25+
.loginPage("/login").permitAll()
26+
.and()
27+
.logout().permitAll();
28+
// @formatter:on
29+
}
30+
31+
@Autowired
32+
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
33+
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
34+
}
35+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
3+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
4+
<head>
5+
<title>Hello World!</title>
6+
</head>
7+
<body>
8+
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
9+
<form th:action="@{/logout}" method="post">
10+
<input type="submit" value="Sign Out"/>
11+
</form>
12+
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
13+
14+
</body>
15+
</html>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html
3+
xmlns="http://www.w3.org/1999/xhtml"
4+
xmlns:th="http://www.thymeleaf.org"
5+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
6+
<head>
7+
<title>Spring Security Example</title>
8+
</head>
9+
<body>
10+
<h1>Welcome!</h1>
11+
12+
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
13+
<p sec:authorize="isAnonymous()">Click <a th:href="@{/register}">here</a> to send a dummy registration request, where the application logs you in.</p>
14+
</body>
15+
</html>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!DOCTYPE html>
2+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
3+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
4+
<head>
5+
<title>Spring Security Example </title>
6+
</head>
7+
<body>
8+
<div th:if="${param.error}">
9+
Invalid username and password.
10+
</div>
11+
<div th:if="${param.logout}">
12+
You have been logged out.
13+
</div>
14+
<form th:action="@{/login}" method="post">
15+
<div><label> User Name : <input type="text" name="username"/> </label></div>
16+
<div><label> Password: <input type="password" name="password"/> </label></div>
17+
<div><input type="submit" value="Sign In"/></div>
18+
</form>
19+
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
20+
</body>
21+
</html>
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Registration could not be completed at this time. Please try again later or contact support!

0 commit comments

Comments
 (0)