Skip to content

Commit 716fcd9

Browse files
author
Eugen
committed
Merge pull request eugenp#20 from corsoft/master
Updated spring-security-mvc-persisted
2 parents d06f8f8 + dd020af commit 716fcd9

File tree

10 files changed

+141
-35
lines changed

10 files changed

+141
-35
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.controller;
2+
3+
import org.springframework.stereotype.Controller;
4+
import org.springframework.web.bind.annotation.RequestMapping;
5+
import org.springframework.web.bind.annotation.RequestMethod;
6+
import org.springframework.web.bind.annotation.RequestParam;
7+
import org.springframework.web.servlet.ModelAndView;
8+
9+
/**
10+
* Web Controller.
11+
*
12+
*/
13+
@Controller
14+
public class MyController {
15+
16+
/**
17+
* Build the view model for the login page (add authentication error
18+
* information in the event of an unsuccessful login attempt).
19+
*/
20+
@RequestMapping(value = "/login", method = RequestMethod.GET)
21+
public ModelAndView login(
22+
@RequestParam(value = "error", required = false) String error) {
23+
24+
ModelAndView model = new ModelAndView();
25+
if (error != null) {
26+
model.addObject("message",
27+
"Username or password not recognised - please try again.");
28+
}
29+
30+
model.setViewName("login");
31+
return model;
32+
33+
}
34+
35+
}

spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,10 @@ protected String determineTargetUrl(final Authentication authentication) {
5454
boolean isAdmin = false;
5555
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
5656
for (final GrantedAuthority grantedAuthority : authorities) {
57-
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
57+
if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_USER.toString())) {
5858
isUser = true;
5959
break;
60-
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
60+
} else if (grantedAuthority.getAuthority().equals(SecurityRole.ROLE_ADMIN.toString())) {
6161
isAdmin = true;
6262
break;
6363
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package org.baeldung.security;
2+
3+
/**
4+
* Simple enum of Security Roles available.
5+
*
6+
*/
7+
public enum SecurityRole {
8+
9+
ROLE_USER,
10+
ROLE_ADMIN;
11+
12+
}

spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import org.apache.commons.logging.Log;
1010
import org.apache.commons.logging.LogFactory;
11+
import org.baeldung.security.SecurityRole;
1112
import org.springframework.security.core.GrantedAuthority;
1213
import org.springframework.security.core.authority.SimpleGrantedAuthority;
1314
import org.springframework.security.core.userdetails.User;
@@ -28,10 +29,8 @@ public class MyUserDetailsService implements UserDetailsService {
2829

2930
public MyUserDetailsService() {
3031

31-
availableUsers.put("user",
32-
createUser("user", "password", Arrays.asList("ROLE_USER")));
33-
availableUsers.put("admin",
34-
createUser("admin", "password", Arrays.asList("ROLE_ADMIN")));
32+
populateDemoUsers();
33+
3534
}
3635

3736
@Override
@@ -49,13 +48,39 @@ public UserDetails loadUserByUsername(String username)
4948

5049
}
5150

52-
private User createUser(String username, String password, List<String> roles) {
51+
/**
52+
* Create demo users (note: obviously in a real system these would be persisted
53+
* in database or retrieved from another system).
54+
*/
55+
private void populateDemoUsers(){
56+
57+
logger.info("Populate demo users");
58+
59+
availableUsers.put("user",
60+
createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER)));
61+
availableUsers.put("admin",
62+
createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN)));
63+
}
64+
65+
66+
/**
67+
* Create a demo User.
68+
*
69+
* @param username
70+
* Username
71+
* @param password
72+
* Password
73+
* @param roles
74+
* Role names user is assigned to
75+
* @return User
76+
*/
77+
private User createUser(String username, String password, List<SecurityRole> roles) {
5378

5479
logger.info("Create user " + username);
5580

5681
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
57-
for (String role : roles) {
58-
authorities.add(new SimpleGrantedAuthority(role));
82+
for (SecurityRole role : roles) {
83+
authorities.add(new SimpleGrantedAuthority(role.toString()));
5984
}
6085
return new User(username, password, true, true, true, true, authorities);
6186
}

spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/spring/SecurityConfig.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package org.baeldung.spring;
22

3+
import org.springframework.beans.factory.annotation.Autowired;
34
import org.springframework.context.annotation.Configuration;
45
import org.springframework.context.annotation.ImportResource;
56
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
67
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
8+
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
79

810
/**
911
* Spring Security Configuration.
@@ -13,8 +15,13 @@
1315
@ImportResource({ "classpath:webSecurityConfig.xml" })
1416
public class SecurityConfig extends WebSecurityConfigurerAdapter {
1517

18+
@Autowired
19+
private AuthenticationSuccessHandler mySimpleUrlAuthenticationSuccessHandler;
20+
1621
public SecurityConfig() {
1722
super();
1823
}
19-
24+
2025
}
26+
27+
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
-- SQL example for H2 (ran automatically by the spring config for the embedded H2 example)
2+
create table if not exists persistent_logins (
3+
username varchar_ignorecase(100) not null,
4+
series varchar(64) primary key,
5+
token varchar(64) not null,
6+
last_used timestamp not null
7+
);
Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
# jdbc.X
1+
# Jdbc H2 configuration
2+
# By default uses the embedded in memory database
3+
# Option provided to use the tcp version if you want to start H2 service and view data
4+
# Chosen database defined in DatabaseConfig.java
25
jdbc.driverClassName=org.h2.Driver
3-
jdbc.url=jdbc:h2:tcp://localhost/~/test
4-
6+
#jdbc.url=jdbc:h2:tcp://localhost/~/testDb
7+
jdbc.url=jdbc:h2:mem:test;MVCC=TRUE
58
jdbc.user=sa
69
jdbc.pass=
710

8-
# hibernate.X
9-
hibernate.dialect=org.hibernate.dialect.H2Dialect
10-
hibernate.show_sql=false
11-
hibernate.hbm2ddl.auto=create-drop
Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
# jdbc.X
1+
# Jdbc PostgreSQL option
2+
# Chosen database defined in DatabaseConfig.java
23
jdbc.driverClassName=org.postgresql.Driver
34
jdbc.url=jdbc:postgresql://localhost:5432
4-
55
jdbc.user=postgres
66
jdbc.pass=
77

8-
# hibernate.X
9-
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
10-
hibernate.show_sql=false
11-
hibernate.hbm2ddl.auto=create-drop

spring-security-mvc-persisted-remember-me/src/main/resources/webSecurityConfig.xml

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55
xmlns:tx="http://www.springframework.org/schema/tx"
66
xmlns:p="http://www.springframework.org/schema/p"
77
xmlns:util="http://www.springframework.org/schema/util"
8+
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
89
xsi:schemaLocation="
910
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
1011
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
1112
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
12-
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
13+
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
14+
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">
1315

1416

1517
<http use-expressions="true">
@@ -25,28 +27,29 @@
2527
<remember-me data-source-ref="dataSource" token-validity-seconds="86400"/>
2628

2729
</http>
30+
31+
<!-- create H2 embedded database table on startup -->
32+
<jdbc:embedded-database id="dataSource" type="H2">
33+
<jdbc:script location="classpath:/persisted_logins_create_table.sql"/>
34+
</jdbc:embedded-database>
2835

29-
30-
31-
36+
<!-- Persistent Remember Me Service -->
3237
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
3338
<beans:property name="key" value="myAppKey" />
3439
<beans:property name="tokenRepository" ref="jdbcTokenRepository" />
3540
<beans:property name="userDetailsService" ref="myUserDetailsService" />
3641
</beans:bean>
37-
38-
<!-- Uses a database table to maintain a set of persistent login data -->
42+
43+
<!-- Uses a database table to maintain a set of persistent login data -->
3944
<beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
4045
<beans:property name="createTableOnStartup" value="false" />
4146
<beans:property name="dataSource" ref="dataSource" />
4247
</beans:bean>
43-
44-
48+
49+
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService)-->
4550
<authentication-manager alias="authenticationManager">
4651
<authentication-provider user-service-ref="myUserDetailsService">
4752
</authentication-provider>
48-
</authentication-manager>
53+
</authentication-manager>
4954

50-
51-
5255
</beans:beans>

spring-security-mvc-persisted-remember-me/src/main/webapp/WEB-INF/view/login.jsp

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
1+
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
12
<html>
2-
<head></head>
3+
<head>
4+
<style>
5+
.message{
6+
margin-top: 20px;
7+
padding: 10px;
8+
color:#FF0000;
9+
border: 1px solid;
10+
border-radius: 2px;
11+
background-color: #F5F6CE;
12+
border-color: #FF0000;
13+
}
14+
</style>
15+
</head>
316

417
<body>
518
<h1>Login</h1>
@@ -23,8 +36,17 @@
2336
<td><input name="submit" type="submit" value="submit" /></td>
2437
</tr>
2538
</table>
39+
40+
41+
<input type="hidden" name="${_csrf.parameterName}"
42+
value="${_csrf.token}" />
2643

2744
</form>
45+
46+
47+
<c:if test="${not empty message}">
48+
<div class="message">${message}</div>
49+
</c:if>
2850

2951
</body>
3052
</html>

0 commit comments

Comments
 (0)