Nik
Nik

Reputation: 638

Spring security user role and access jsp

I am new to spring security. I have two user roles like Admin and Common Users. I want to access some jsp only access by the admin users, but the problem is once a user is log out he/she still can access the jsp page which i put restricted in spring security config.

Let me know what i am doing here is the correct or not?

Thank you

spring_security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <http auto-config="true">
        <intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
        <intercept-url pattern="/user/**" access="ROLE_USER" />

        <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/loginfailed" />
        <logout logout-success-url="/logout" />
    </http>


    <beans:bean id="customUserDetailsService"
        class="com.nikunj.javabrains.services.CustomUserDetailsService"></beans:bean>

    <authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService">
        </authentication-provider>
    </authentication-manager>

//------------------------------ Controller

package com.nikunj.javabrains.controller;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nikunj.javabrains.domain.User;
import com.nikunj.javabrains.services.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String printWelcome(ModelMap model, Principal principal,
            HttpServletRequest request) {

        String name = principal.getName(); // get logged in username
        model.addAttribute("username", name);
        model.addAttribute("message",
                "Spring Security login + database example");

        if (request.isUserInRole("ROLE_ADMIN")) {
            return "admin_page";
        }
        return "common_page";

    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap model) {

        return "login";

    }

    @RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
    public String loginerror(ModelMap model) {

        model.addAttribute("error", "true");
        return "login";

    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(ModelMap model) {

        return "login";

    }

    @RequestMapping("/regiPage")
    public String regiPage(@ModelAttribute("user") User user,
            BindingResult result) {

        return "registration";
    }

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public String saveUserData(@ModelAttribute("user") User user,
            BindingResult result) {

        userService.addUser(user);
        return "login";

    }

}



    </beans:beans>

//------------------------

CustomServiceClass

import com.nikunj.javabrains.dao.UserDao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly=true)
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDAO;    

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        com.nikunj.javabrains.domain.User domainUser = userDAO.getUser(username);

        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        System.out.println("*************************************");
        System.out.println(domainUser.getId());

        return new User(
                domainUser.getUsername(), 
                domainUser.getPassword(), 
                enabled, 
                accountNonExpired, 
                credentialsNonExpired, 
                accountNonLocked,
                getAuthorities(domainUser.getId())


        );



    }

    public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
        List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
        return authList;
    }

    public List<String> getRoles(Integer role) {

        List<String> roles = new ArrayList<String>();

        if (role.intValue() == 1) {
            roles.add("ROLE_ADMIN");
        } else {
            roles.add("ROLE_USER");
        }
        return roles;
    }

    public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

}

//---------------------------

@Controller
public class AdminController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/admininput", method = RequestMethod.GET)
    public String login(ModelMap model) {
        System.out.println("*************************");
        return "admininputpage";
    }

}

Upvotes: 0

Views: 5324

Answers (2)

Amit kumar
Amit kumar

Reputation: 11

you can use unique session id in url .if destroy session after logout or by copying url,URL can't be accessible without login URL with logged session.

Upvotes: 1

rhinds
rhinds

Reputation: 10043

Ok, so as per your last comment, the URL /admininput is being accessed by everyone.

This is the behaviour I would expect, as there is no security rules defined for this URL pattern.

In your security config you define the following rules:

<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/user/**" access="ROLE_USER" />

This config will require all resources with the URL pattern /admin/** to be logged in with role ROLE_ADMIN and all resources with URL pattern /user/** to be logged in with role ROLE_USER. All other URL patterns will be permitAll.

If you want to restrict that URL you will either need to change the URL pattern, or add an intercept rule. E.g.

Change URL from /admininput to /admin/input or /admin/admininput etc

Alternatively, add an explicit intercept rule (or another pattern based rule) to cover this URL:

<intercept-url pattern="/admininput" access="ROLE_ADMIN" />

(although, not a good idea to have explicit interceptor rules for every URL! so would be better to change URL if possible to the convention you already defined)

Upvotes: 1

Related Questions