[BAEL-9552] - Create spring-security-modules folder
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
## Spring Security ACL
|
||||
|
||||
This module contains articles about Spring Security ACL
|
||||
|
||||
### Relevant Articles
|
||||
- [Introduction to Spring Security ACL](https://www.baeldung.com/spring-security-acl)
|
||||
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-security-acl</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-security-acl</name>
|
||||
<packaging>war</packaging>
|
||||
<description>Spring Security ACL</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-1</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-acl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.ehcache</groupId>
|
||||
<artifactId>ehcache-core</artifactId>
|
||||
<version>${ehcache-core.version}</version>
|
||||
<type>jar</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<ehcache-core.version>2.6.11</ehcache-core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.acl;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package org.baeldung.acl.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.cache.ehcache.EhCacheFactoryBean;
|
||||
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
|
||||
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
|
||||
import org.springframework.security.acls.AclPermissionCacheOptimizer;
|
||||
import org.springframework.security.acls.AclPermissionEvaluator;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
|
||||
import org.springframework.security.acls.domain.ConsoleAuditLogger;
|
||||
import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy;
|
||||
import org.springframework.security.acls.domain.EhCacheBasedAclCache;
|
||||
import org.springframework.security.acls.jdbc.BasicLookupStrategy;
|
||||
import org.springframework.security.acls.jdbc.JdbcMutableAclService;
|
||||
import org.springframework.security.acls.jdbc.LookupStrategy;
|
||||
import org.springframework.security.acls.model.PermissionGrantingStrategy;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
public class ACLContext {
|
||||
|
||||
@Autowired
|
||||
DataSource dataSource;
|
||||
|
||||
@Bean
|
||||
public EhCacheBasedAclCache aclCache() {
|
||||
return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EhCacheFactoryBean aclEhCacheFactoryBean() {
|
||||
EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
|
||||
ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject());
|
||||
ehCacheFactoryBean.setCacheName("aclCache");
|
||||
return ehCacheFactoryBean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EhCacheManagerFactoryBean aclCacheManager() {
|
||||
return new EhCacheManagerFactoryBean();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PermissionGrantingStrategy permissionGrantingStrategy() {
|
||||
return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AclAuthorizationStrategy aclAuthorizationStrategy() {
|
||||
return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN"));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
|
||||
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
|
||||
AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService());
|
||||
expressionHandler.setPermissionEvaluator(permissionEvaluator);
|
||||
expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
|
||||
return expressionHandler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LookupStrategy lookupStrategy() {
|
||||
return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JdbcMutableAclService aclService() {
|
||||
return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package org.baeldung.acl.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
||||
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
|
||||
public class AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
|
||||
|
||||
@Autowired
|
||||
MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler;
|
||||
|
||||
@Override
|
||||
protected MethodSecurityExpressionHandler createExpressionHandler() {
|
||||
return defaultMethodSecurityExpressionHandler;
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.baeldung.acl.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao")
|
||||
@PropertySource("classpath:org.baeldung.acl.datasource.properties")
|
||||
@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" })
|
||||
public class JPAPersistenceConfig {
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package org.baeldung.acl.persistence.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.acl.persistence.entity.NoticeMessage;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.security.access.prepost.PostAuthorize;
|
||||
import org.springframework.security.access.prepost.PostFilter;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
|
||||
public interface NoticeMessageRepository extends JpaRepository<NoticeMessage, Long>{
|
||||
|
||||
@PostFilter("hasPermission(filterObject, 'READ')")
|
||||
List<NoticeMessage> findAll();
|
||||
|
||||
@PostAuthorize("hasPermission(returnObject, 'READ')")
|
||||
NoticeMessage findById(Integer id);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@PreAuthorize("hasPermission(#noticeMessage, 'WRITE')")
|
||||
NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage);
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package org.baeldung.acl.persistence.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="system_message")
|
||||
public class NoticeMessage {
|
||||
|
||||
@Id
|
||||
@Column
|
||||
private Integer id;
|
||||
@Column
|
||||
private String content;
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
INSERT INTO acl_sid (id, principal, sid) VALUES
|
||||
(1, 1, 'manager'),
|
||||
(2, 1, 'hr'),
|
||||
(3, 0, 'ROLE_EDITOR');
|
||||
|
||||
INSERT INTO acl_class (id, class) VALUES
|
||||
(1, 'org.baeldung.acl.persistence.entity.NoticeMessage');
|
||||
|
||||
INSERT INTO system_message(id,content) VALUES
|
||||
(1,'First Level Message'),
|
||||
(2,'Second Level Message'),
|
||||
(3,'Third Level Message');
|
||||
|
||||
INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES
|
||||
(1, 1, 1, NULL, 3, 0),
|
||||
(2, 1, 2, NULL, 3, 0),
|
||||
(3, 1, 3, NULL, 3, 0);
|
||||
|
||||
INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES
|
||||
(1, 1, 1, 1, 1, 1, 1, 1),
|
||||
(2, 1, 2, 1, 2, 1, 1, 1),
|
||||
(3, 1, 3, 3, 1, 1, 1, 1),
|
||||
(4, 2, 1, 2, 1, 1, 1, 1),
|
||||
(5, 2, 2, 3, 1, 1, 1, 1),
|
||||
(6, 3, 1, 3, 1, 1, 1, 1),
|
||||
(7, 3, 2, 3, 2, 1, 1, 1);
|
||||
@@ -0,0 +1,58 @@
|
||||
create table IF NOT EXISTS system_message (id integer not null, content varchar(255), primary key (id));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS acl_sid (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
principal tinyint(1) NOT NULL,
|
||||
sid varchar(100) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY unique_uk_1 (sid,principal)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS acl_class (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
class varchar(255) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY unique_uk_2 (class)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS acl_entry (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
acl_object_identity bigint(20) NOT NULL,
|
||||
ace_order int(11) NOT NULL,
|
||||
sid bigint(20) NOT NULL,
|
||||
mask int(11) NOT NULL,
|
||||
granting tinyint(1) NOT NULL,
|
||||
audit_success tinyint(1) NOT NULL,
|
||||
audit_failure tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS acl_object_identity (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
object_id_class bigint(20) NOT NULL,
|
||||
object_id_identity bigint(20) NOT NULL,
|
||||
parent_object bigint(20) DEFAULT NULL,
|
||||
owner_sid bigint(20) DEFAULT NULL,
|
||||
entries_inheriting tinyint(1) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity)
|
||||
);
|
||||
|
||||
ALTER TABLE acl_entry
|
||||
ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id);
|
||||
|
||||
ALTER TABLE acl_entry
|
||||
ADD FOREIGN KEY (sid) REFERENCES acl_sid(id);
|
||||
|
||||
--
|
||||
-- Constraints for table acl_object_identity
|
||||
--
|
||||
ALTER TABLE acl_object_identity
|
||||
ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id);
|
||||
|
||||
ALTER TABLE acl_object_identity
|
||||
ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id);
|
||||
|
||||
ALTER TABLE acl_object_identity
|
||||
ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id);
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
|
||||
spring.h2.console.path=/myconsole
|
||||
spring.h2.console.enabled=true
|
||||
spring.datasource.initialize=true
|
||||
spring.datasource.schema=classpath:acl-schema.sql
|
||||
spring.datasource.data=classpath:acl-data.sql
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.baeldung;
|
||||
|
||||
import org.baeldung.acl.Application;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package org.baeldung.acl;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.baeldung.acl.persistence.dao.NoticeMessageRepository;
|
||||
import org.baeldung.acl.persistence.entity.NoticeMessage;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.TestExecutionListeners;
|
||||
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
|
||||
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
|
||||
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
|
||||
import org.springframework.test.context.web.ServletTestExecutionListener;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
|
||||
DependencyInjectionTestExecutionListener.class,
|
||||
DirtiesContextTestExecutionListener.class,
|
||||
TransactionalTestExecutionListener.class,
|
||||
WithSecurityContextTestExecutionListener.class})
|
||||
public class SpringACLIntegrationTest extends AbstractJUnit4SpringContextTests{
|
||||
|
||||
private static Integer FIRST_MESSAGE_ID = 1;
|
||||
private static Integer SECOND_MESSAGE_ID = 2;
|
||||
private static Integer THIRD_MESSAGE_ID = 3;
|
||||
private static String EDITTED_CONTENT = "EDITED";
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("org.baeldung.acl.*")
|
||||
public static class SpringConfig {
|
||||
|
||||
}
|
||||
|
||||
@Autowired
|
||||
NoticeMessageRepository repo;
|
||||
|
||||
@Test
|
||||
@WithMockUser(username="manager")
|
||||
public void givenUserManager_whenFindAllMessage_thenReturnFirstMessage(){
|
||||
List<NoticeMessage> details = repo.findAll();
|
||||
assertNotNull(details);
|
||||
assertEquals(1,details.size());
|
||||
assertEquals(FIRST_MESSAGE_ID,details.get(0).getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username="manager")
|
||||
public void givenUserManager_whenFind1stMessageByIdAndUpdateItsContent_thenOK(){
|
||||
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
|
||||
assertNotNull(firstMessage);
|
||||
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
|
||||
|
||||
firstMessage.setContent(EDITTED_CONTENT);
|
||||
repo.save(firstMessage);
|
||||
|
||||
NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID);
|
||||
assertNotNull(editedFirstMessage);
|
||||
assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId());
|
||||
assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username="hr")
|
||||
public void givenUsernameHr_whenFindMessageById2_thenOK(){
|
||||
NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID);
|
||||
assertNotNull(secondMessage);
|
||||
assertEquals(SECOND_MESSAGE_ID,secondMessage.getId());
|
||||
}
|
||||
|
||||
@Test(expected=AccessDeniedException.class)
|
||||
@WithMockUser(username="hr")
|
||||
public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){
|
||||
NoticeMessage secondMessage = new NoticeMessage();
|
||||
secondMessage.setId(SECOND_MESSAGE_ID);
|
||||
secondMessage.setContent(EDITTED_CONTENT);
|
||||
repo.save(secondMessage);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(roles={"EDITOR"})
|
||||
public void givenRoleEditor_whenFindAllMessage_thenReturn3Message(){
|
||||
List<NoticeMessage> details = repo.findAll();
|
||||
assertNotNull(details);
|
||||
assertEquals(3,details.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(roles={"EDITOR"})
|
||||
public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){
|
||||
NoticeMessage thirdMessage = new NoticeMessage();
|
||||
thirdMessage.setId(THIRD_MESSAGE_ID);
|
||||
thirdMessage.setContent(EDITTED_CONTENT);
|
||||
repo.save(thirdMessage);
|
||||
}
|
||||
|
||||
@Test(expected=AccessDeniedException.class)
|
||||
@WithMockUser(roles={"EDITOR"})
|
||||
public void givenRoleEditor_whenFind1stMessageByIdAndUpdateContent_thenFail(){
|
||||
NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID);
|
||||
assertNotNull(firstMessage);
|
||||
assertEquals(FIRST_MESSAGE_ID,firstMessage.getId());
|
||||
firstMessage.setContent(EDITTED_CONTENT);
|
||||
repo.save(firstMessage);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
## Spring Security Angular
|
||||
|
||||
This module contains articles about Spring Security with Angular
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular)
|
||||
@@ -0,0 +1,40 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
angular
|
||||
.module('app', ['ngRoute'])
|
||||
.config(config)
|
||||
.run(run);
|
||||
|
||||
config.$inject = ['$routeProvider', '$locationProvider'];
|
||||
function config($routeProvider, $locationProvider) {
|
||||
$routeProvider
|
||||
.when('/', {
|
||||
controller: 'HomeController',
|
||||
templateUrl: 'home/home.view.html',
|
||||
controllerAs: 'vm'
|
||||
})
|
||||
.when('/login', {
|
||||
controller: 'LoginController',
|
||||
templateUrl: 'login/login.view.html',
|
||||
controllerAs: 'vm'
|
||||
})
|
||||
.otherwise({ redirectTo: '/login' });
|
||||
}
|
||||
|
||||
run.$inject = ['$rootScope', '$location', '$http', '$window'];
|
||||
function run($rootScope, $location, $http, $window) {
|
||||
var userData = $window.sessionStorage.getItem('userData');
|
||||
if (userData) {
|
||||
$http.defaults.headers.common['Authorization'] = 'Basic ' + JSON.parse(userData).authData;
|
||||
}
|
||||
|
||||
$rootScope.$on('$locationChangeStart', function (event, next, current) {
|
||||
var restrictedPage = $.inArray($location.path(), ['/login']) === -1;
|
||||
var loggedIn = $window.sessionStorage.getItem('userData');;
|
||||
if (restrictedPage && !loggedIn) {
|
||||
$location.path('/login');
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
angular
|
||||
.module('app')
|
||||
.controller('HomeController', HomeController);
|
||||
|
||||
HomeController.$inject = ['$window', '$http', '$scope'];
|
||||
function HomeController($window, $http, $scope) {
|
||||
var vm = this;
|
||||
|
||||
vm.user = null;
|
||||
|
||||
initController();
|
||||
|
||||
function initController() {
|
||||
|
||||
$http({
|
||||
url: 'http://localhost:8082/user',
|
||||
method: "GET"
|
||||
}).then(function (response) {
|
||||
vm.user = response.data.name;
|
||||
},function(error){
|
||||
console.log(error);
|
||||
});
|
||||
};
|
||||
|
||||
$scope.logout = function(){
|
||||
$window.sessionStorage.setItem('userData', '');
|
||||
$http.defaults.headers.common['Authorization'] = 'Basic';
|
||||
}
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,3 @@
|
||||
<h1>Hi {{vm.user}}!</h1>
|
||||
<p>You're logged in!!</p>
|
||||
<p><a href="#!/login" class="btn btn-primary" ng-click="logout()">Logout</a></p>
|
||||
@@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html ng-app="app">
|
||||
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
<div ng-view></div>
|
||||
|
||||
<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
|
||||
<script src="//code.angularjs.org/1.6.0/angular.min.js"></script>
|
||||
<script src="//code.angularjs.org/1.6.0/angular-route.min.js"></script>
|
||||
<script src="app.js"></script>
|
||||
<script src="home/home.controller.js"></script>
|
||||
<script src="login/login.controller.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
angular
|
||||
.module('app')
|
||||
.controller('LoginController', LoginController);
|
||||
|
||||
LoginController.$inject = ['$location', '$window', '$http'];
|
||||
function LoginController($location, $window, $http) {
|
||||
var vm = this;
|
||||
vm.login = login;
|
||||
|
||||
(function initController() {
|
||||
$window.localStorage.setItem('token', '');
|
||||
})();
|
||||
|
||||
function login() {
|
||||
$http({
|
||||
url: 'http://localhost:8082/login',
|
||||
method: "POST",
|
||||
data: { 'userName': vm.username, 'password': vm.password }
|
||||
}).then(function (response) {
|
||||
if (response.data) {
|
||||
var token = $window.btoa(vm.username + ':' + vm.password);
|
||||
var userData = {
|
||||
userName: vm.username,
|
||||
authData: token
|
||||
}
|
||||
$window.sessionStorage.setItem('userData', JSON.stringify(userData));
|
||||
$http.defaults.headers.common['Authorization'] = 'Basic ' + token;
|
||||
$location.path('/');
|
||||
} else {
|
||||
alert("Authentication failed.")
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,18 @@
|
||||
<div>
|
||||
<h2>Login</h2>
|
||||
<form name="form" ng-submit="vm.login()" role="form">
|
||||
<div>
|
||||
<label for="username">Username</label>
|
||||
<input type="text" name="username" id="username" ng-model="vm.username" required />
|
||||
<span ng-show="form.username.$dirty && form.username.$error.required">Username is required</span>
|
||||
</div>
|
||||
<div>
|
||||
<label for="password">Password</label>
|
||||
<input type="password" name="password" id="password" ng-model="vm.password" required />
|
||||
<span ng-show="form.password.$dirty && form.password.$error.required">Password is required</span>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
a {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.help-block {
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<div class="jumbotron">
|
||||
<div class="container">
|
||||
<div class="col-sm-8 col-sm-offset-2">
|
||||
<router-outlet></router-outlet>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app',
|
||||
templateUrl: './app/app.component.html'
|
||||
})
|
||||
|
||||
export class AppComponent { }
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpModule } from '@angular/http';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
import { routing } from './app.routing';
|
||||
|
||||
import { HomeComponent } from './home/home.component';
|
||||
import { LoginComponent } from './login/login.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
FormsModule,
|
||||
HttpModule,
|
||||
routing
|
||||
],
|
||||
declarations: [
|
||||
AppComponent,
|
||||
HomeComponent,
|
||||
LoginComponent
|
||||
],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
|
||||
export class AppModule { }
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Routes, RouterModule } from '@angular/router';
|
||||
|
||||
import { HomeComponent } from './home/home.component';
|
||||
import { LoginComponent } from './login/login.component';
|
||||
|
||||
const appRoutes: Routes = [
|
||||
{ path: '', component: HomeComponent},
|
||||
{ path: 'login', component: LoginComponent },
|
||||
{ path: '**', redirectTo: '' }
|
||||
];
|
||||
|
||||
export const routing = RouterModule.forRoot(appRoutes);
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
<div>
|
||||
<h1>Hi {{userName}}!</h1>
|
||||
<p><a [routerLink]="['/login']" (click) ="logout()">Logout</a></p>
|
||||
</div>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Http, RequestOptions, Headers } from '@angular/http';
|
||||
import 'rxjs/add/operator/map'
|
||||
|
||||
@Component({
|
||||
selector:'home',
|
||||
templateUrl: './app/home/home.component.html'
|
||||
})
|
||||
|
||||
export class HomeComponent implements OnInit {
|
||||
|
||||
userName: string;
|
||||
|
||||
constructor(private http: Http) { }
|
||||
|
||||
ngOnInit() {
|
||||
let url = 'http://localhost:8082/user';
|
||||
let headers = new Headers({
|
||||
'Authorization': 'Basic ' + sessionStorage.getItem('token')
|
||||
});
|
||||
let options = new RequestOptions({ headers: headers });
|
||||
this.http.post(url,{}, options).
|
||||
map(res => res.json()).
|
||||
subscribe(
|
||||
principal => this.userName = principal.name,
|
||||
error => {
|
||||
if(error.status == 401)
|
||||
alert('Unauthorized');
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
logout() {
|
||||
sessionStorage.setItem('token', '');
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<div class="col-md-6 col-md-offset-3">
|
||||
<h2>Login</h2>
|
||||
<form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
|
||||
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
|
||||
<label for="username">Username</label>
|
||||
<input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
|
||||
<div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
|
||||
</div>
|
||||
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
|
||||
<label for="password">Password</label>
|
||||
<input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
|
||||
<div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button [disabled]="loading" class="btn btn-primary">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Router, ActivatedRoute } from '@angular/router';
|
||||
import { Http } from '@angular/http';
|
||||
|
||||
@Component({
|
||||
selector: 'login',
|
||||
templateUrl: './app/login/login.component.html'
|
||||
})
|
||||
|
||||
export class LoginComponent implements OnInit {
|
||||
model: any = {};
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private http: Http) { }
|
||||
|
||||
ngOnInit() {
|
||||
sessionStorage.setItem('token', '');
|
||||
}
|
||||
|
||||
login() {
|
||||
let url = 'http://localhost:8082/login';
|
||||
let result = this.http.post(url, {
|
||||
userName: this.model.username,
|
||||
password: this.model.password
|
||||
}).map(res => res.json()).subscribe(isValid => {
|
||||
if (isValid) {
|
||||
sessionStorage.setItem('token', btoa(this.model.username + ':' + this.model.password));
|
||||
this.router.navigate(['']);
|
||||
} else {
|
||||
alert("Authentication failed.");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user