@PreAuthorize不使用spring security 4

时间:2016-01-12 09:58:52

标签: spring-mvc spring-security

我遇到了@PreAuthorize注释的问题。有两件事要做。

  • 检索所有员工应由具有USERADMIN权限的人员完成。

  • 删除员工应由权限ADMIN的员工完成。 我需要使用spring-security-4方法级别授权。

Project_explorer_view

User.java

package com.nikunj.SpringMethodLevelAuthorization;
public class user {
    int id;
    String firstName;
    String type;

    public user(int id, String firstName, String type){
        this.id = id;
        this.firstName = firstName;
        this.type = type;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}

userService.java

package com.nikunj.SpringMethodLevelAuthorization;
import java.util.Vector;
import org.springframework.security.access.prepost.PreAuthorize;
public interface userService {
    @PreAuthorize("hasRole('ADMIN')")
    public void deleteUser(int id);

    @PreAuthorize("hasRole('ADMIN') or hasRole('USER')")
    public Vector<user> getAllUsers();
}

userImplementation.java

package com.nikunj.SpringMethodLevelAuthorization;
import java.util.Vector;
public class userImplementation implements userService {
    Vector<user> users; 
    public userImplementation(){
        users = new Vector<user>();
        users.add(new user(1,"Nikunj","SE"));
        users.add(new user(2,"Abdul","SSE"));
        users.add(new user(3,"Mrinal","LSE"));
        users.add(new user(4,"Anurag","SE"));
        users.add(new user(5,"Naresh","LSE"));
        users.add(new user(6,"Mahesh","SE"));
    }

    public user findById(int id){
        for(user u : users){
            if(u.getId()==id){
                return u;
            }
        }
        return null;
    }

    public Vector<user> getAllUsers(){
        return users;
    }

    public void deleteUser(int id){
        user u = findById(id);
        users.remove(u);
    }
}

homeController.java

package com.nikunj.SpringMethodLevelAuthorization;

import java.util.Vector;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
    userImplementation ui=new userImplementation();
    Vector<user> users;

    @RequestMapping(value = { "/users" },method = RequestMethod.GET)
    public String getAllUsers(Model model) {
        System.out.println("in getAll()");
        users=ui.getAllUsers();
        model.addAttribute("users", users);
        return "allUsers";
    }


    @RequestMapping(value = { "/delete/{id}" }, method = RequestMethod.GET)
    public String deleteUser(@PathVariable int id,Model model){
        System.out.println("in delete()");
        ui.deleteUser(id);
        users=ui.getAllUsers();
        model.addAttribute("users", users);
        return "allUsers";  
    }   
}

调度-servlet.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.nikunj.SpringMethodLevelAuthorization" />
</beans:beans>

弹簧security.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true">
        <intercept-url pattern="/" access="hasRole('USER') or hasRole('ADMIN')" />
    </http> 

    <!-- Eable method level security -->
    <global-method-security pre-post-annotations="enabled"/>    

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="abdul" password="root123" authorities="ROLE_ADMIN"/>
                <user name="nikunj" password="secret" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
                     /WEB-INF/dispatcher-servlet.xml
                     /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring Security Configuration -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

1 个答案:

答案 0 :(得分:0)

将userImplementation设为Spring bean,并通过注释或在xml中定义它,将其注入HomeController。

<beans:bean name="userService" class="com.nikunj.SpringMethodLevelAuthorization.userImplementation" />

OR

@Service
public class userImplementation implements userService {
....
....
}

然后在HomeController中自动装配它。

@Controller
public class HomeController {
    //userImplementation ui=new userImplementation();
    @Autowired
    UserService ui;
 ......
 ......
}