<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 使用 JUnit 測試 Spring Security Auth > 原文: [https://howtodoinjava.com/junit/how-to-unit-test-spring-security-authentication-with-junit/](https://howtodoinjava.com/junit/how-to-unit-test-spring-security-authentication-with-junit/) 學習使用`InMemoryDaoImpl`使用 JUnit 測試用例測試 Spring Security認證。 還學習以編程方式構建完全填充的`authentication`對象,然后在應用程序中使用它。 ## `SecurityContextHolder` Spring Security 基于安全性上下文,本質上是靜態的。 從本質上講,這意味著您無需將其引用注入到 spring 容器中的 bean 或類中。 您只需使用[`SecurityContextHolder.getContext()`](http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/context/SecurityContextHolder.html#getContext%28%29)方法即可隨時訪問 spring 上下文。 該上下文具有實際主體或用戶的引用,我們必須對其訪問權限進行驗證。 ## Spring Security 單元測試 我正在創建一個[簡單的 Maven 項目](https://howtodoinjava.com/maven/create-a-simple-java-project-using-maven/),并且將編寫最少的代碼,以便我可以專注于僅測試此帖子范圍內的內容,即身份驗證。 然后,我將用一個需要“ `ROLE_USER`”的單一方法編寫一個演示服務類。 如果嘗試訪問此方法而沒有“ `ROLE_USER`”,則將獲得預期的`AccessDeniedException`。 很簡單,不是嗎? #### 步驟 1)創建項目 讓我們使用以下命令創建 Java 項目: `Console` ```java $ mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=SpringPasswordHashingDemo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false ``` 現在,使用以下依賴項更新`pom.xml`,并運行命令`mvn:eclipse:eclipse`以支持項目 Eclipse。 `pom.xml` ```java <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava</groupId> <artifactId>SpringPasswordHashingDemo</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>SpringPasswordHashingDemo</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>3.0.5.RELEASE</org.springframework.version> </properties> <dependencies> <!-- Spring Core --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.4</version> <scope>test</scope> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${org.springframework.version}</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> </project> ``` #### 步驟 2)創建安全配置文件 我創建了`application-security.xml`文件,并將安全配置放入其中。 `application-security.xml` ```java <?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-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> <global-method-security secured-annotations="enabled" /> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="lokesh" password="password1" authorities="ROLE_USER" /> <user name="admin" password="password2" authorities="ROLE_ADMIN" /> </user-service> </authentication-provider> </authentication-manager> <beans:bean id="demoService" class="com.howtodoinjava.DemoService"/> </beans:beans> ``` #### 步驟 3)建立受保護的方法 `DemoService.java` ```java package com.howtodoinjava; import org.springframework.security.access.annotation.Secured; public class DemoService { @Secured("ROLE_USER") public void method() { System.out.println("Method called"); } } ``` #### 步驟 4)使用 JUnit 測試身份驗證 在 junit 測試中,我們將以編程方式配置 spring 上下文,然后將通過默認用戶詳細信息服務中的用戶名訪問用戶。 在極端情況下,它是**內存中實現**,在您的情況下,它可能與某些[基于 jdbc 的用戶詳細信息服務](https://howtodoinjava.com/spring/spring-security/jdbc-user-service-based-spring-security-example/)或某些其他[自定義用戶詳細信息服務](https://howtodoinjava.com/spring/spring-security/custom-userdetailsservice-example-for-spring-3-security/)不同。 因此,請相應地修改查找。 我們將測試各種方案,例如有效用戶,無效用戶,無效角色等。您可以根據選擇添加/刪除方案。 `TestDemoService.java` ```java package com.howtodoinjava; import java.util.ArrayList; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.memory.InMemoryDaoImpl; public class TestDemoService { static ApplicationContext applicationContext = null; static InMemoryDaoImpl userDetailsService = null; /** * Initialize the application context to re-use in all test cases * */ @BeforeClass public static void setup() { //Create application context instance applicationContext = new ClassPathXmlApplicationContext("application-security.xml"); //Get user details service configured in configuration userDetailsService = applicationContext.getBean(InMemoryDaoImpl.class); } /** * Test the valid user with valid role * */ @Test public void testValidRole() { //Get the user by username from configured user details service UserDetails userDetails = userDetailsService.loadUserByUsername ("lokesh"); Authentication authToken = new UsernamePasswordAuthenticationToken (userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authToken); DemoService service = (DemoService) applicationContext.getBean("demoService"); service.method(); } /** * Test the valid user with INVALID role * */ @Test (expected = AccessDeniedException.class) public void testInvalidRole() { UserDetails userDetails = userDetailsService.loadUserByUsername ("lokesh"); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_INVALID")); Authentication authToken = new UsernamePasswordAuthenticationToken (userDetails.getUsername(), userDetails.getPassword(), authorities); SecurityContextHolder.getContext().setAuthentication(authToken); DemoService service = (DemoService) applicationContext.getBean("demoService"); service.method(); } /** * Test the INVALID user * */ @Test (expected = AccessDeniedException.class) public void testInvalidUser() { UserDetails userDetails = userDetailsService.loadUserByUsername ("admin"); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new GrantedAuthorityImpl("ROLE_INVALID")); Authentication authToken = new UsernamePasswordAuthenticationToken (userDetails.getUsername(), userDetails.getPassword(), authorities); SecurityContextHolder.getContext().setAuthentication(authToken); DemoService service = (DemoService) applicationContext.getBean("demoService"); service.method(); } } ``` 如您所見,所有測試用例均按預期通過。 學習快樂! [**源碼下載**](https://docs.google.com/file/d/0B7yo2HclmjI4akNlUVdXNDJtdDA/edit?usp=sharing)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看