Skip to content

Commit 0d599ae

Browse files
chrisoberleKevinGilmore
authored andcommitted
import source BAEL-1084 (eugenp#2560)
1 parent fd37ffb commit 0d599ae

23 files changed

Lines changed: 1028 additions & 0 deletions
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.baeldung.rolesauthorities;
2+
3+
import org.baeldung.rolesauthorities.model.User;
4+
import org.baeldung.rolesauthorities.persistence.UserRepository;
5+
import org.springframework.security.authentication.BadCredentialsException;
6+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
8+
import org.springframework.security.core.Authentication;
9+
import org.springframework.security.core.AuthenticationException;
10+
import org.springframework.security.core.userdetails.UserDetailsService;
11+
12+
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {
13+
14+
private final UserRepository userRepository;
15+
@SuppressWarnings("unused")
16+
private UserDetailsService userDetailsService;
17+
18+
public CustomAuthenticationProvider(UserRepository userRepository, UserDetailsService userDetailsService){
19+
super();
20+
this.setUserDetailsService(userDetailsService);
21+
this.userRepository = userRepository;
22+
}
23+
24+
@Override
25+
public Authentication authenticate(Authentication auth) throws AuthenticationException {
26+
final User user = userRepository.findByEmail(auth.getName());
27+
if ((user == null)) {
28+
throw new BadCredentialsException("Invalid username or password");
29+
}
30+
final Authentication result = super.authenticate(auth);
31+
return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities());
32+
}
33+
34+
@Override
35+
public boolean supports(Class<?> authentication) {
36+
return authentication.equals(UsernamePasswordAuthenticationToken.class);
37+
}
38+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package org.baeldung.rolesauthorities;
2+
3+
import java.io.IOException;
4+
5+
import javax.servlet.ServletException;
6+
import javax.servlet.http.HttpServletRequest;
7+
import javax.servlet.http.HttpServletResponse;
8+
import javax.servlet.http.HttpSession;
9+
10+
import org.springframework.security.core.Authentication;
11+
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
12+
import org.springframework.stereotype.Component;
13+
14+
@Component("myLogoutSuccessHandler")
15+
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
16+
17+
@Override
18+
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
19+
final HttpSession session = request.getSession();
20+
if (session != null) {
21+
session.removeAttribute("user");
22+
}
23+
24+
response.sendRedirect("/");
25+
}
26+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package org.baeldung.rolesauthorities;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collection;
5+
import java.util.List;
6+
7+
import org.baeldung.rolesauthorities.model.Privilege;
8+
import org.baeldung.rolesauthorities.model.Role;
9+
import org.baeldung.rolesauthorities.model.User;
10+
import org.baeldung.rolesauthorities.persistence.UserRepository;
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.security.core.GrantedAuthority;
13+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
14+
import org.springframework.security.core.userdetails.UserDetails;
15+
import org.springframework.security.core.userdetails.UserDetailsService;
16+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
17+
import org.springframework.stereotype.Service;
18+
import org.springframework.transaction.annotation.Transactional;
19+
20+
@Service("userDetailsService")
21+
@Transactional
22+
public class MyUserDetailsService implements UserDetailsService {
23+
24+
@Autowired
25+
private UserRepository userRepository;
26+
27+
public MyUserDetailsService() {
28+
super();
29+
}
30+
31+
// API
32+
33+
@Override
34+
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
35+
36+
try {
37+
final User user = userRepository.findByEmail(email);
38+
if (user == null) {
39+
throw new UsernameNotFoundException("No user found with username: " + email);
40+
}
41+
org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), user.isEnabled(), true, true, true, getAuthorities(user.getRoles()));
42+
return userDetails;
43+
} catch (final Exception e) {
44+
throw new RuntimeException(e);
45+
}
46+
}
47+
48+
// UTIL
49+
50+
private final Collection<? extends GrantedAuthority> getAuthorities(final Collection<Role> roles) {
51+
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
52+
for (Role role: roles) {
53+
authorities.add(new SimpleGrantedAuthority(role.getName()));
54+
for (Privilege privilege: role.getPrivileges()) {
55+
authorities.add(new SimpleGrantedAuthority(privilege.getName()));
56+
}
57+
}
58+
return authorities;
59+
}
60+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package org.baeldung.rolesauthorities;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
5+
import org.springframework.boot.web.support.SpringBootServletInitializer;
6+
import org.springframework.context.annotation.ComponentScan;
7+
import org.springframework.context.annotation.Configuration;
8+
9+
@Configuration
10+
@EnableAutoConfiguration
11+
@ComponentScan("org.baeldung.rolesauthorities")
12+
public class RolesAuthoritiesApplication extends SpringBootServletInitializer {
13+
public static void main(String[] args) {
14+
System.setProperty("spring.profiles.default", "rolesauthorities");
15+
SpringApplication.run(RolesAuthoritiesApplication.class, args);
16+
}
17+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.baeldung.rolesauthorities.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
6+
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
7+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8+
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
9+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
10+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
11+
12+
@Configuration
13+
@EnableWebMvc
14+
public class MvcConfig extends WebMvcConfigurerAdapter {
15+
16+
public MvcConfig() {
17+
super();
18+
}
19+
20+
//
21+
@Bean
22+
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
23+
return new PropertySourcesPlaceholderConfigurer();
24+
}
25+
26+
@Override
27+
public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
28+
configurer.enable();
29+
}
30+
31+
@Override
32+
public void addViewControllers(final ViewControllerRegistry registry) {
33+
super.addViewControllers(registry);
34+
registry.addViewController("/").setViewName("forward:/home");
35+
registry.addViewController("/protectedbynothing").setViewName("rolesauthorities/protectedbynothing");
36+
registry.addViewController("/protectedbyrole").setViewName("rolesauthorities/protectedbyrole");
37+
registry.addViewController("/protectedbyauthority").setViewName("rolesauthorities/protectedbyauthority");
38+
registry.addViewController("/login").setViewName("rolesauthorities/login");
39+
registry.addViewController("/home").setViewName("rolesauthorities/home");
40+
registry.addViewController("/logout");
41+
}
42+
43+
@Override
44+
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
45+
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
46+
}
47+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package org.baeldung.rolesauthorities.config;
2+
3+
import org.baeldung.rolesauthorities.CustomAuthenticationProvider;
4+
import org.baeldung.rolesauthorities.persistence.UserRepository;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.ComponentScan;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
10+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
11+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12+
import org.springframework.security.config.annotation.web.builders.WebSecurity;
13+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
14+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
15+
import org.springframework.security.core.userdetails.UserDetailsService;
16+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
17+
import org.springframework.security.crypto.password.PasswordEncoder;
18+
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
19+
20+
@Configuration
21+
@ComponentScan(basePackages = { "org.baeldung.rolesauthorities" })
22+
@EnableWebSecurity
23+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
24+
25+
@Autowired
26+
private UserRepository userRepository;
27+
28+
@Autowired
29+
private UserDetailsService userDetailsService;
30+
31+
@Autowired
32+
private LogoutSuccessHandler myLogoutSuccessHandler;
33+
34+
public SecurityConfig() {
35+
super();
36+
}
37+
38+
@Override
39+
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
40+
auth.authenticationProvider(authProvider());
41+
}
42+
43+
@Override
44+
public void configure(final WebSecurity web) throws Exception {
45+
web.ignoring()
46+
.antMatchers("/resources/**");
47+
}
48+
49+
50+
@Override
51+
protected void configure(final HttpSecurity http) throws Exception {
52+
53+
// @formatter:off
54+
http
55+
.csrf().disable()
56+
.authorizeRequests()
57+
.antMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll()
58+
.antMatchers("/protectedbyrole").hasRole("USER")
59+
.antMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE")
60+
.and()
61+
.formLogin()
62+
.loginPage("/login")
63+
.failureUrl("/login?error=true")
64+
.permitAll()
65+
.and()
66+
.logout()
67+
.logoutSuccessHandler(myLogoutSuccessHandler)
68+
.invalidateHttpSession(false)
69+
.logoutSuccessUrl("/logout.html?logSucc=true")
70+
.deleteCookies("JSESSIONID")
71+
.permitAll();
72+
// @formatter:on
73+
}
74+
75+
// beans
76+
77+
@Bean
78+
public DaoAuthenticationProvider authProvider() {
79+
final CustomAuthenticationProvider authProvider
80+
= new CustomAuthenticationProvider(userRepository, userDetailsService);
81+
authProvider.setPasswordEncoder(encoder());
82+
return authProvider;
83+
}
84+
85+
@Bean
86+
public PasswordEncoder encoder() {
87+
return new BCryptPasswordEncoder(11);
88+
}
89+
90+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package org.baeldung.rolesauthorities.model;
2+
3+
import java.util.Collection;
4+
5+
import javax.persistence.Entity;
6+
import javax.persistence.GeneratedValue;
7+
import javax.persistence.GenerationType;
8+
import javax.persistence.Id;
9+
import javax.persistence.ManyToMany;
10+
11+
@Entity
12+
public class Privilege {
13+
14+
@Id
15+
@GeneratedValue(strategy = GenerationType.AUTO)
16+
private Long id;
17+
18+
private String name;
19+
20+
@ManyToMany(mappedBy = "privileges")
21+
private Collection<Role> roles;
22+
23+
public Privilege() {
24+
super();
25+
}
26+
27+
public Privilege(final String name) {
28+
super();
29+
this.name = name;
30+
}
31+
32+
//
33+
34+
public Long getId() {
35+
return id;
36+
}
37+
38+
public void setId(final Long id) {
39+
this.id = id;
40+
}
41+
42+
public String getName() {
43+
return name;
44+
}
45+
46+
public void setName(final String name) {
47+
this.name = name;
48+
}
49+
50+
public Collection<Role> getRoles() {
51+
return roles;
52+
}
53+
54+
public void setRoles(final Collection<Role> roles) {
55+
this.roles = roles;
56+
}
57+
58+
@Override
59+
public int hashCode() {
60+
final int prime = 31;
61+
int result = 1;
62+
result = prime * result + ((name == null) ? 0 : name.hashCode());
63+
return result;
64+
}
65+
66+
@Override
67+
public boolean equals(Object obj) {
68+
if (this == obj)
69+
return true;
70+
if (obj == null)
71+
return false;
72+
if (getClass() != obj.getClass())
73+
return false;
74+
Privilege other = (Privilege) obj;
75+
if (name == null) {
76+
if (other.name != null)
77+
return false;
78+
} else if (!name.equals(other.name))
79+
return false;
80+
return true;
81+
}
82+
83+
@Override
84+
public String toString() {
85+
final StringBuilder builder = new StringBuilder();
86+
builder.append("Privilege [name=").append(name).append("]").append("[id=").append(id).append("]");
87+
return builder.toString();
88+
}
89+
}

0 commit comments

Comments
 (0)