1

I am a beginner in spring MVC framework and I am building an application in which I have a role and role have different permissions on different screen .like:- on Dashboard user have two permissions (Read and write) and in second screen page user have (Read , Write and Create) permission. so just want to know how could I put this permission with the session to get these in with the screen type at each screen when I am checking the permission or another method to do this process in a more effective way.

 this my user validation code at login time:- 




  public String validate(String userName, String password, HttpServletResponse response, HttpServletRequest request,
                Model model) {
            logger.debug("Starting of the method validate");
            System.out.println("validate");

            Session session = null;

            try {
                AppConfig aapConfig = new AppConfig();
                List<UsersTable> userList = aapConfig.findAll(UsersTable.class);

                System.out.println("############userList length is " +userList.size());

                if (!userList.isEmpty()) {
                    System.out.println("*****************UserList is not emptry");
                    Map<String, UsersTable> userMap = userList.stream().filter(e -> e.getUsername() != null)
                            .collect(Collectors.toMap(e -> e.getUsername(), e -> e, (x, y) -> x));

                    if (userMap.containsKey(userName)) {
                        UsersTable user = userMap.get(userName);
                        if (StringUtils.equals(EncryptDecryptPassword.decrypt(user.getUserpassword(), "AirtelSiva"),
                                password)) {
                            String userFullName = user.getUserfirstname();
                            String circleId = user.getUsercircle();
                            System.out.println("&&&&&&&&&& Circle ID is "+circleId);
                            HttpSession httpSession =request.getSession();
                            String id = httpSession.getId();
                            System.out.println(id);
                            httpSession.setAttribute("userFullName", userFullName);
                            httpSession.setAttribute("userName", userName);
                            httpSession.setAttribute("circleId", circleId);

                            // saving the userName with the unique session Id
                            UserSession userSession = new UserSession();
                            userSession.setUserName(userName);
                            userSession.setSessionId(id);
    return"";
    }
yash
  • 51
  • 1
  • 9

1 Answers1

2

With spring-security, you can provide this authorization with minimal effort. Add the required dependencies to your POM and configure the authentication. Keep in mind, when adding the spring-security dependency, its version should be compatible with the spring version you are using.

You can simply provide authentication and authorization like

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure( AuthenticationManagerBuilder auth ) throws Exception
    {
     // Using in-memory authentication
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        auth.inMemoryAuthentication()
            .withUser( users.username( "john" ).password( "john1234" ).roles( "READ", "WRITE" ) )
            .withUser( users.username( "doe" ).password( "doe1234" ).roles( "READ", "WRITE", "CREATE" ) );
    }

    /**
     * This allows adding custom login-form and add HTTP URL security
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure( HttpSecurity http ) throws Exception
    {
        http.authorizeRequests()
            .antMatchers( "/" ).permitAll()
            .antMatchers( "/dashboard" ).hasAnyRole( "READ","WRITE" )
            .antMatchers( "/anotherPage" ).hasAnyRole( "READ","WRITE","CREATE" )
            .anyRequest()
            .authenticated()
            .and()
            .formLogin() // Add form login
            .loginPage( "/showMyLoginPage" ) // Pointing to custom login form. This line is optional as spring by default provides a login page
            .loginProcessingUrl( "/authenticateTheUser" ) // No coding needed. Just provide some endpoint. You need not implement this endpoint. Spring will take care of it.
            .permitAll()
            // Other necessary validations like CSRF or cookie policy
}

Please find the tutorial on the spring official doc here.

And once you do the authorization with Spring-security. You can ask your template engine [if it support]. to show or hide certain sections of the page depending on the roles of the logged user.

As an example, here's how you could hide a link based on the user role in JSP by adding the security support like <%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Here, only users having role ADMIN can see this link.

<security:authorize access="hasRole('ADMIN')">
    <hr>
    <p><a href="${pageContext.request.contextPath}/admin">Link to admin page</a> ( Only admin can see this )</p>
    <hr>
</security:authorize>

This link contain all the necessary detail to get started on spring-security.

Klaus
  • 1,641
  • 1
  • 10
  • 22
  • hey, Klaus, I am not using spring secutrity I am an HTTP session to check the login by validating the user by my code. I added my login validation code in my question – yash May 04 '20 at 07:13
  • 1
    I strongly suggest you to use `spring-security`. Otherwise, you'll endup doing lot more error prone work. I have edited the code to add login support as well. Nice thing in this approach is most of the heavily lifting is done by spring. They even provide a login form out of the box. – Klaus May 04 '20 at 07:34
  • ok, thank you so much klaus it's really helpful for me, i want to ask one more thing for the views that I need to hide some contents in views how it will work according to the permissions. please suggest – yash May 04 '20 at 07:54
  • 1
    That can be done with spring security tags and that depends on your template engine. I have used JSP and Thymeleaf and they support this. I have included a section in my answer to this also. Please look into that. Also if you find this answer helpful, please mark this as an accepted answer – Klaus May 04 '20 at 08:27
  • hey Klaus, not meeting my requirement yet please suggest more like, how can we bind the permissions with role screen by screen, like in roles with each user we just adding the role once. and this will same for all screen in your case, but in my case role change according to the screen, like:- he can access only Task page, but in secound page he can do write and read both , – yash May 04 '20 at 12:26
  • My idea is your definition of roles is not correct. For example, please do assign valid roles like `USER` which can do user related stuff, `ADMIN` which can do admin related stuff, a user having the roles `USER, ADMIN` can perform both these actions. Thats how you must define your users – Klaus May 04 '20 at 15:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213131/discussion-between-yash-and-klaus). – yash May 05 '20 at 05:11