Spring Security 4.0 ÜyeGirisFormu-Database

Eclipse Neon
Tomcat v9.0
Jdk 1.8
SpringFramework 4.0
SpringSecurity 4.0
Eclips teki dosya yapısı aşağıdaki gibidir
Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

// HomeController.java

package com.ismailfedakar.controller;

import org.springframework.security.authentication.AnonymousAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.servlet.ModelAndView;

@Controller

public class HomeController {

//Serbest bölge

@RequestMapping(value = { "/", "/hosgeldin**" }, method = RequestMethod.GET)

public ModelAndView nerhabaSayfasi() {

ModelAndView model = new ModelAndView();

model.addObject("baslik", "SprinSecurity4.0 Üye Giriş!");

model.addObject("mesaj", "Burası Hoş geldin Sayfası!");

model.setViewName("merhaba");

return model;

}

//Yönetici girişini denetler

@RequestMapping(value = "/yonetim**", method = RequestMethod.GET)

public ModelAndView yonetimSayfasi() {

ModelAndView model = new ModelAndView();

model.addObject("baslik", "SprinSecurity4.0 Üye Giriş!");

model.addObject("mesaj", "Burası Korumalı (protected) Sayfa!");

model.setViewName("yonetim");

return model;

}

//Üye girişini denetler

@RequestMapping(value = "/giris", method = RequestMethod.GET)

public ModelAndView girisSayfasi(@RequestParam(value = "hata", required = false) String hata,

@RequestParam(value = "cikis", required = false) String cikis) {

ModelAndView model = new ModelAndView();

if (hata != null) {

model.addObject("hata", "Giriş işlemi başarısız! , Bilgilerinizi kontrol edin!");

}

if (cikis != null) {

model.addObject("msg", "Başarı ile çıkış Yaptınız.");

}

model.setViewName("giris");

return model;

}

//hata sayfasını denetler

@RequestMapping(value = "/403", method = RequestMethod.GET)

public ModelAndView accesssDenied() {

ModelAndView model = new ModelAndView();

//kullanıcı girişini denetler

Authentication girisKontrol = SecurityContextHolder.getContext().getAuthentication();

if (!(girisKontrol instanceof AnonymousAuthenticationToken)) {

UserDetails kullaniciDetay = (UserDetails) girisKontrol.getPrincipal();

System.out.println(kullaniciDetay);

model.addObject("username", kullaniciDetay.getUsername());

}

model.setViewName("403");

return model;

}

}

//merhaba.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@page session="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Merhaba Sayfası</title>

</head>

<body>

<center>

<div align="center">

<h1>Başlık : ${baslik}</h1>

<h1>Mesaj : ${mesaj}</h1>

</div>

</center>

</body>

</html>

//giris.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Üye Giriş Sayfası</title>

</head>

<body onload='document.loginForm.username.focus();'>

<center>

<h1>SprinSecurity4.0_UyeGirisFormu</h1>

<br>

<div align="center">

<c:if test="${not empty hata}">

<div class="hata">

<h3 style="color: red;">${hata}</h3>

</div>

</c:if>

<c:if test="${not empty msg}">

<div class="msg">

<h3 style="color: red;">${msg}</h3>

</div>

<br>

</c:if>

<h3>Kullanıcı Adı ve Şifrenizi Giriniz!</h3>

<form name='loginForm'

action="<c:url value='/j_spring_security_check' />" method='POST'>

<table>

<tr>

<td>Kullanıcı Adı :</td>

<td><input type='text' name='username'></td>

</tr>

<tr>

<td>Kullanıcı Sifre:</td>

<td><input type='password' name='password' /></td>

</tr>

<tr>

<td colspan='2'><input name="submit" type="submit"

value="Giriş Yap" /></td>

</tr>

</table>

<input type="hidden" name="${_csrf.parameterName}"

value="${_csrf.token}" />

</form>

</div>

</center>

</body>

</html>

//yonetim.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@page session="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Yönetici Sayfası</title>

</head>

<body>

<div align="center">

<h1>Başlık : ${baslik}</h1>

<h1>Masaj : ${mesaj}</h1>

<c:url value="/j_spring_security_logout" var="logoutUrl" />

<form action="${logoutUrl}" method="POST" id="logoutForm">

<input type="hidden" name="${_csrf.parameterName}"

value="${_csrf.token}" />

</form>

<script>

function formSubmit() {

document.getElementById("logoutForm").submit();

}

</script>

<c:if test="${pageContext.request.userPrincipal.name != null}">

<h2>

Welcome : ${pageContext.request.userPrincipal.name} | <a

href="javascript:formSubmit()"> Çıkış Yap</a>

</h2>

</c:if>

</div>

</body>

</html>

//403.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@page session="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>HATA!</title>

</head>

<body onload="setTimeout('bekleBiraz()',5000)">

<center>

<div align="center" style="width: 500px">

<h1 style="background:lime; color: red;">Yetkisiz Giriş!</h1>

<c:if test="${pageContext.request.userPrincipal.name != null}">

<h2>

Merhaba : ${pageContext.request.userPrincipal.name} - Bey/Hanım

</h2>

</c:if>

<h2><span style="color: red;">Hata</span><br>Bu sayfaya girme yetkiniz yok!..</h2>

</div>

</center>

<script type="text/javascript">

function bekleBiraz()

{

window.location = "http://localhost:8080/SpringSecurity/giris"

}

</script>

<center>

<h2 style="color: red;">Yönlendiriliyorsunuz!</h2>

<p>5 saniye içerisinde yeni sayfamıza yönlendirileceksiniz!</p>

</center>

</body>

</html>

//mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!--Spring Konteyner Annotationları dikkate alacak-->

<context:component-scan base-package="com.ismailfedakar.*" />

<!--Birden fazla Bean ımız olabilir-->

<context:annotation-config/>

<!--Autowired Configuration RequestMapping vs. aktif-->

<tx:annotation-driven />

<!--Standart yapılandırma-->

<bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<!--Ana dizinimiz /WEB-INF/pages/-->

<value>/WEB-INF/sayfalar/</value>

</property>

<property name="suffix">

<!--Sayfa uzantılarımız .jsp olacak-->

<value>.jsp</value>

</property>

</bean>

</beans>

//spring-database.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">

<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<!--Veritabanı bağlantısını bu propertyler sayesinde yapıyoruz.-->

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3307/guvenlik" />

<property name="username" value="root" />

<property name="password" value="root" />

</bean>

</beans>

//spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:security="http://www.springframework.org/schema/security"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<!--use-expressions aktif Rolleri Yapılandırabilmek için-->

<security:http auto-config="true" use-expressions="true">

<!--/yönetim sayfasını admin rölüne sahip olanlar görebilecek-->

<security:intercept-url pattern="/yonetim**" access="hasRole('ROLE_ADMIN')"/>

<!--hata oluşursa 403.jsp sayfasına yönlendir-->

<security:access-denied-handler error-page="/403"/>

<!--giriş.jsp sayfasındaki işlemlerini kontrol eden tag-->

<security:form-login

login-page="/giris"

default-target-url="/hosgeldin"

authentication-failure-url="/giris?hata"

username-parameter="username"

password-parameter="password"

login-processing-url="/j_spring_security_check" />

<!--giriş.jsp sayfasındaki logout (çıkış) işlemlerini kontrol eden tag-->

<security:logout

logout-url="/j_spring_security_logout"

invalidate-session="true"

logout-success-url="/giris?cikis" />

<!-- (csrf) Güvenlik taraması aktif-->

<security:csrf/>

</security:http>

<!-- Kullanıcılar ve kullanıcı rollerini veritabanından konrtol ediyoruz -->

<security:authentication-manager>

<security:authentication-provider>

<security:jdbc-user-service data-source-ref="dataSource"

users-by-username-query=

"select kullaniciAdi,sifre, onay from kullanicilar where kullaniciAdi=?"

authorities-by-username-query=

"select kullaniciAdi, rol from roller where kullaniciAdi =? " />

</security:authentication-provider>

</security:authentication-manager>

</beans>

//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

<display-name>SprinSecurity4.0_UyeGirisFormu-Database</display-name>

<servlet>

<servlet-name>mvc-dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>mvc-dispatcher</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/spring-security.xml,

/WEB-INF/spring-database.xml

</param-value>

</context-param>

<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>

//pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"

xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<modelVersion>4.0.0</modelVersion>

<groupId>com.ismailfedakar</groupId>

<artifactId>SprinSecurity4.0_UyeGirisFormu-Database</artifactId>

<packaging>war</packaging>

<version>1.0-SNAPSHOT</version>

<name>SprinSecurity4.0_UyeGirisFormu-Database-Database</name>

<url>http://www.ismailfedakar.com/</url>

<licenses>

<license>

<name>The Apache Software License, Version 2.0</name>

<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>

<distribution>repo</distribution>

</license>

</licenses>

<properties>

<jdk.version>1.8</jdk.version>

<spring.version>4.0.0.RELEASE</spring.version>

<spring.security.version>4.0.0.RELEASE</spring.security.version>

<jstl.version>1.2</jstl.version>

<mysql.connector.version>5.1.18</mysql.connector.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>${spring.version}</version>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-web</artifactId>

<version>${spring.security.version}</version>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-config</artifactId>

<version>${spring.security.version}</version>

</dependency>

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-taglibs</artifactId>

<version>${spring.security.version}</version>

</dependency>

<dependency>

<groupId>jstl</groupId>

<artifactId>jstl</artifactId>

<version>${jstl.version}</version>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>${mysql.connector.version}</version>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>2.3.2</version>

<configuration>

<source>${jdk.version}</source>

<target>${jdk.version}</target>

</configuration>

</plugin>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-eclipse-plugin</artifactId>

<version>2.9</version>

<configuration>

<downloadSources>true</downloadSources>

<downloadJavadocs>false</downloadJavadocs>

<wtpversion>2.0</wtpversion>

</configuration>

</plugin>

</plugins>

</build>

</project>

Projeyi çalıştıdığımızda görüntümüz aşağıdaki gibi olacak.

Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

Tarayıcıdaki linki şu şekilde değiştirelim

http://localhost:8080/SprinSecurity4.0_UyeGirisFormu/giris

Karşımıza şu ekran gelecek

Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

ROLE_USER yetkisine sahip olan k.adı=fedakar şifre=123 ile giriş yapalım.

Aşağıdaki görüntü gelecek

Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

Hoşgeldin etiketi spring-security.xml de dikkat ederseniz access=“permitAll” olarak tanımlanmıştır. Yani buraya ROLE_USER ve ROLE_ADMIN yetkisine sahip tüm kullanıcılar ulaşabilmektedir. Sıkıntı
Yok.
Şimdi linkimizi şu şekilde değiştirelim. http://localhost:8080/SprinSecurity4.0_UyeGirisFormu/yonetim

Karşımıza şöyle bir görüntü gelecek.

Javascript BirazBekle();

metodu ile giriş.jsp ye yönlendirme yapıyoruz. Çünkü kullanıcı ROLE_USER yetkisine sahip

Sonraki ekran görüntüsü

Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

Şimdide ROLE_ADMIN yetkisine sahip k.adı=fedakar şifresi=123 olan admin yetkisine sahip kullanıcı ile giriş yapalım. Ekran görüntümüz aşağıdaki gibi olacak

Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

Şimdi tekrar Linkimi şu şekilde yapalım

http://localhost:8080/SprinSecurity4.0_UyeGirisFormu/yonetim

Görüntümüz aşağıdaki gibi olacak



Spring Security 4.0 | UyeGirisFormu | Database

Spring Security 4.0 | UyeGirisFormu | Database

Çıkış Yap butonuna tıklarsanız tekrar giriş sayfasına yönlenirsiniz.

Bu günlükte bu kadar.

Github Source Code

Benzer İçerikler

JSF EĞİTİM SETİ

WordPress

Blogger

Soysal Medyada Paylaş