π Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
π Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
//get user from the database, via Hibernate
@Autowired
private UserDao userDao;
@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
//CUSTOM USER HERE vvv
User user = userDao.findByUserName(username);
List < GrantedAuthority > authorities =
buildUserAuthority(user.getUserRole());
//if you're implementing UserDetails you wouldn't need to call this method and instead return the User as it is
//return buildUserForAuthentication(user, authorities);
return user;
}
// Converts user to spring.springframework.security.core.userdetails.User
private User buildUserForAuthentication(user,
List < GrantedAuthority > authorities) {
return new User(user.getUsername(), user.getPassword(),
user.isEnabled(), true, true, true, authorities);
}
private List < GrantedAuthority > buildUserAuthority(Set < UserRole > userRoles) {
Set < GrantedAuthority > setAuths = new HashSet < GrantedAuthority > ();
// add user's authorities
for (UserRole userRole: userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List < GrantedAuthority > Result = new ArrayList < GrantedAuthority > (setAuths);
return Result;
}
}
Access User Roles in JSP using Spring Security
1. Maven Dependencies
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
Declaring the Taglibs
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
Print User Roles in JSP Page
<sec:authentication property="principal.authorities"/>
Access Expressions
<sec:authorize access="!isAuthenticated()">
Login
</sec:authorize>
<sec:authorize access="isAuthenticated()">
Logout
</sec:authorize>
<sec:authorize access="hasRole('ADMIN')">
Manage Users
</sec:authorize>
Display Logged in User in JSP
<sec:authorize access="isAuthenticated()">
Welcome Back, <sec:authentication property="name"/>
</sec:authorize>
Comments
Post a Comment
Leave Comment