Java活用生活

ログイン

オンライン状況

オンラインユーザー1人
ログインユーザー0人
登録ユーザー2人

カウンタ

COUNTER332348

日誌

Web Master
123456
2024/04/20

Spring Security Version6以降の対応について

固定リンク | by:aramaki
Spring Securityを利用して、ログイン処理を実装しようと、以下のサイトを
参考に、実装したが、すでにバージョンが、6以降になっていて、削除されたクラスも
あり、作成できないため、改めて作成しました。
尚、ログインページは、Springの自動作成ページではなく、自作の「login2.html」
、またDBはORCL19Cです。

【Java・SpringBoot】Springセキュリティ④ - ログイン処理の実装
https://qiita.com/suema0331/items/886c0345c9a6172c64ac


【実装コード】SecurityConfig.java
--------------------------------------------------------------------------------------------------------
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;


@EnableWebSecurity 
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
// パスワードエンコーダーBean
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
   
    // 認証するユーザーの情報をデータベースからロードする
String userSql="select user_Id,password, 1 as ENABLED from Account where user_Id=?";// Oracleにboolean型がない
String roleSql="select user_Id,ACCOUNT_GROUP as ROLE from Account  where user_Id=?";

    AuthenticationManagerBuilder authBuilder=http.getSharedObject(AuthenticationManagerBuilder.class);
    authBuilder.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(userSql)
.authoritiesByUsernameQuery(roleSql)
    .passwordEncoder(passwordEncoder());
   
    // バージョンログ
    String springSecurityVersion = SpringSecurityCoreVersion.getVersion();
    System.out.println("Spring Security Version: " + springSecurityVersion);
      
// ログインページ設定
http.authorizeHttpRequests(
authz -> authz.requestMatchers("/css/**").permitAll()
.requestMatchers("/js/**").permitAll()
.requestMatchers("/login2").permitAll()
.requestMatchers("/admin/").permitAll()
.requestMatchers("/signup").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN") // admin権限しかアクセスできない。
.anyRequest().authenticated() // 上記URL以外は認証が必要
);
// ログイン処理
http.formLogin(login -> login  //HttpSecurity
.loginProcessingUrl("/login2") // ログイン処理Path
.loginPage("/login2")
.failureUrl("/login2") // ログイン認証失敗時の遷移先
.usernameParameter("userId")
.passwordParameter("password")
.defaultSuccessUrl("/home",true) 
.permitAll());

        // ログアウト処理
        http.logout(logout -> logout
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login2")
                // セッション無効化
                .deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll());
        // CRFS対策を無効
        http.csrf(csrf -> csrf.disable());

return http.build();
}
    
}

11:33 | 投票する | 投票数(0) | コメント(0)
2024/02/11

Spring pom.xmlにJAXBなど使用できるようにする

固定リンク | by:aramaki
Spring pom.xmlにJAXBなど使用できるようにする。
----------------------------------------------------------------------
<!-- JAXB -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- JPAによるデータベースの利用 Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

22:01 | 投票する | 投票数(0) | コメント(0)
2023/03/08

簡易ログ表示関数

固定リンク | by:aramaki
簡易ログ表示関数
-------------------------------------
 void log(String message) {
System.out.printf("[%s] %s%n", LocalDateTime.now(), message);
 }
12:01 | 投票する | 投票数(0) | コメント(0)
2023/02/26

Jquery select 選択値で、別のselectのoptionを変更

固定リンク | by:aramaki
jQuery select 選択値で、別のselectのoptionを変更
----------------------------------------------------------------------------

実行結果
ここをクリック

----------------------------
     ソースコード
----------------------------

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
    <script type="text/javascript">
      $(function(){
        let data0 =[{name:"",id:"0"}];

        let data1=[{name:"",id:"0"},{name:"東京",id:"1"},{name:"大阪",id:"2"},{name:"京都",id:"3"}];

        let data2=[{name:"",id:"0"},{name:"ワシントン",id:"1"},{name:"シアトル",id:"2"},{name:"コロラド",id:"3"}];

        let data3=[{name:"",id:"0"},{name:"北京",id:"1"},{name:"上海",id:"2"},{name:"香港",id:"3"}];

        let city_data = undefined;

        // 地域エリアを選択した場合、対応するオプションがselect要素に設定する。
        $('[name = area]').on('change',function(){
          let area_val = $(this).val();
          
          switch(area_val){
            case "0" :
            city_data = data0;
            break;
            case "1":
            city_data = data1;
            break;
            case "2" :
            city_data = data2;
            break;
            case "3" :
            city_data = data3;
            break;
            default:
              break;

          }
            // selectタグのoption値を一旦削除
            $('[name = city] option').remove();
            // 新たにoptionを設定する。
            let selectItem = "";
            $.each(city_data,function(index,data){
              
              $('[name = city]').append($('<option>').text(data.name).val(data.id));
              if(index == 1){
                // data1 data2 data3の2番目の値を選択状態にする。
                selectItem = data.id;
              }             

            });

            $('[name = city] option').attr("selected", false);

            $('[name = city]').val(selectItem);

            $('[name = city]').selectmenu('refresh');             
 
        })
        
      });


    </script>
  </head>

  <body>
    <div>
      <div class="form">
       <form name="country" >
        <label for="area_name">国名</label>
        
        <select id="area_name" name="area" size="1">
            <option value="0"></option>
            <option value="1">日本</option>
            <option value="2">アメリカ</option>
            <option value="3">中国</option>
        </select>
        <label for="city _name">都市名</label>
        <select id="city _name" name="city" size="1">
            <option value="0"></option>
            <option value="1">ワシントン</option>
            <option value="2">シアトル</option>
            <option value="3">コロラド</option>
        </select>

       </form>
    </div>
  </body>
</html>






21:16 | 投票する | 投票数(0) | コメント(0)
2023/02/12

javascriptファイル取込(Node.js)

固定リンク | by:aramaki
javascriptファイル取込(Node.js)
----------------------------------------------
inc,js
------------------------
exports.func=function() {

    return "BOO";

};

sample,js
---------------------------------
const User=require('./inc.js');

(async () =>{
 console.log(User.func());

})()


21:44 | 投票する | 投票数(0) | コメント(0)
2023/02/04

Node SQL トランザクション参考

固定リンク | by:aramaki
Node SQL トランザクション参考
------------------------------------------------------

18:29 | 投票する | 投票数(0) | コメント(0)
2023/02/04

Node.js でOracleアクセス

固定リンク | by:aramaki
Node.js でOracleアクセス
---------------------------------------
1.node.jsからoracleへ接続するためのモジュールをインストール
npm i oracledb

2.Oracle Instant Client をダウンロード

3.サンプルコード
------------
const dbConfig={
    user       : '××',
    password   : '××',
    connectionString : '192.168.××.××:1521/pdborcl2'
}

const oracledb=require('oracledb')

let parameter;
let connection;
let result;

(async () =>{
    
    try {
        oracledb.initOracleClient({libDir: 'D:\\instantclient_21_8'});
        let sql='select ename from emp where empno =:empno';
        parameter=[7655];
        connection=await oracledb.getConnection({
            user : dbConfig.user,
            password : dbConfig.password,
            connectionString : dbConfig.connectionString
        });
        options = {outFormat: oracledb.OUT_FORMAT_OBJECT};
        console.log('Connected Start');

        if(connection){
            result = await connection.execute(sql,parameter,options);
            console.log(result.rows);
        }

    } catch (error) {
        console.log("ERROR"+error);
    }finally{
        await connection.close();
    }
})()
4.実行

node cndb.js
PS C:\Users\Aramaki\OneDrive\デスクトップ\MyDoc\jstest> node condb.js
Connected Start
[ { ENAME: '山田' } ]
PS C:\Users\Aramaki\OneDrive\デスクトップ\MyDoc\jstest>






13:57 | 投票する | 投票数(0) | コメント(0)
2023/01/30

エラー処理

固定リンク | by:aramaki
Dim i As Long
On Error Resume Next
i = "AAA"
If Err.Number <> 0 Then
  MsgBox Err.Description
  Err.Clear
End If
MsgBox Err.Number
23:06 | 投票する | 投票数(0) | コメント(0)
2023/01/30

VBScript ファイルの読み込み

固定リンク | by:aramaki
VBScript ファイルの読み込み
--------------------------------------
Option Explicit


Dim objFSO
Dim objFile
Dim arrLines
Dim cnt
Dim strTemp
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("E:\data.txt")

'Do While objFile.AtEndOfLine <> True
Do Until objFile.AtEndOfStream
    arrLines = objFile.ReadLine
    strTemp = Mid(arrLines,12,2)
    MsgBox strTemp
    If(strTemp="12") Then
    cnt = cnt + 1
    End If
Loop
WScript.Echo cnt

objFile.close()
Set objFile = Nothing

'ファイルシステムオブジェクトの破棄
objFSO = Nothing
21:06 | 投票する | 投票数(0) | コメント(0)
2023/01/05

HTTPで画像をダウンロード

固定リンク | by:aramaki
HTTPで画像をダウンロード
-----------------------------------------

public class DownImage {

private static final String targetContentType = "image/png";
private static final String InputData = "http://k.yimg.jp/images/top/sp2/cmn/logo-ns-131205.png";

public static void main(String[] args) {

InputStream inputStream=null;
OutputStream outputStream=null;
BufferedInputStream bufferedInputStream=null;
BufferedOutputStream bufferedOutputStream=null;
try{
// URL読込処理
URL url=new URL(InputData);
// inputStream=url.openConnection().getInputStream();
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
// 接続時にユーザー名やパスワードの入力を求められたとき、許可をするかどうか
connection.setAllowUserInteraction(false);// 許可しない
// キャッシュの使用を許可するか
connection.setUseCaches(false);// 許可しない
// プロトコルがリダイレクトに従うかどうか
connection.setInstanceFollowRedirects(true);// 従う

// HTTPに使用するメソッド
connection.setRequestMethod("GET");
// 接続
connection.connect();
// 結果コード
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
// コンテンツタイプ
if(connection.getContentType().equals(targetContentType)){
inputStream=connection.getInputStream();
}else{
throw new Exception("ContentType " + connection.getContentType());
}
}else{
throw new Exception("HTTP Status " + connection.getResponseCode());
}

bufferedInputStream=new BufferedInputStream(inputStream);

// 書込み処理
outputStream=new FileOutputStream("logo.png");
bufferedOutputStream=new BufferedOutputStream(outputStream);

int len;
byte[] b=new byte[2048];
while((len=bufferedInputStream.read(b))!=-1){
bufferedOutputStream.write(b,0,len);
bufferedOutputStream.flush();
}

}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
} catch (Exception e) {

e.printStackTrace();
}finally {
try{
if(bufferedOutputStream!=null){
bufferedOutputStream.close();
}
if(bufferedInputStream!=null){
bufferedInputStream.close();
}
}catch(Exception e){

}
}

}
23:35 | 投票する | 投票数(0) | コメント(0)
123456
Copyright © Java活用生活 All Rights Reserved .